Java Android-ListView在setContentView()之后消失?

Java Android-ListView在setContentView()之后消失?,java,android,xml,listview,android-listview,Java,Android,Xml,Listview,Android Listview,我的一个activity_main.xml文件中有一个ListView,问题是,当我单击该ListView(activity_main.xml)中的一个项目时,它调用setContentView()并加载另一个名为activity_settings.xml的xml文件 问题是,当我单击activity_settings.xml中的后退按钮(再次调用setContentView()并返回activity_main.xml的按钮)时,activity_main.xml中的ListView将消失 我试

我的一个activity_main.xml文件中有一个ListView,问题是,当我单击该ListView(activity_main.xml)中的一个项目时,它调用setContentView()并加载另一个名为activity_settings.xml的xml文件

问题是,当我单击activity_settings.xml中的后退按钮(再次调用setContentView()并返回activity_main.xml的按钮)时,activity_main.xml中的ListView将消失

我试过十几种方法来修复它,但似乎都不管用

这是我的MainActivity.java(它相当大):

package com.NautGames.xectav2.app;
导入{…}
公共类MainActivity扩展了ASR{
私人开关按钮自动关闭;
***
int键码;
关键事件;
语境;
私有静态最终字符串LOGTAG=“Xecta”;
私有静态最终字符串BOTID=“e38006d97e34053e”;
私人TTS myTts;
专用图像按钮speakButton;
私人Bot;
按钮1;
按钮2;
按钮3;
布尔mBound=false;
simpledappter simpledpt;
BoundService myService=新的BoundService();
布尔值isBound=false;
编辑文本名称、电子邮件、消息、主题;
字符串键;
字符串名;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent Intent=新Intent(这个,BoundService.class);
bindService(intent、myConnection、Context.BIND\u AUTO\u CREATE);
//homeOnOff=(ToggleButton)findViewById(R.id.ToggleButton);
name=(EditText)findViewById(R.id.etName);
email=(EditText)findViewById(R.id.etEmail);
mMessage=(EditText)findViewById(R.id.etAdd);
subject=(EditText)findViewById(R.id.txtSubject);
按钮startBtn=(按钮)findViewById(R.id.send);
backB1=(按钮)findViewById(R.id.button1);
backB2=(按钮)findViewById(R.id.button2);
backB3=(按钮)findViewById(R.id.button3);
//初始化GUI元素
设置峰值按钮();
//初始化语音识别器
CreateRecognitor(getApplicationContext());
//将文本初始化为语音
myTts=TTS.getInstance(this);
//创建机器人
bot=新bot(此,BOTID,myTts,“助理”);
initList();
//我们从布局中获取ListView组件
ListView lv=(ListView)findViewById(R.id.ListView);
//这是一个简单的适配器,可接受为参数
//上下文
//数据表
//创建行期间使用的行布局
//用于检索数据的键
//用于显示数据的视图id。键号和视图id必须匹配
simpleAdpt=new SimpleAdapter(这个,planetsList,android.R.layout.simple_list_item_1,新字符串[]{“page”},新int[]{android.R.id.text1});
低压设置适配器(simpleAdpt);
//对用户单击项目作出反应
lv.setOnItemClickListener(新的AdapterView.OnItemClickListener()
{
public void onItemClick(适配器视图父适配器、视图视图、int位置、,
长id)
{
//我们知道该视图是文本视图,因此可以将其转换为文本视图
TextView点击查看=(TextView)查看;
//Toast.makeText(MainActivity.this,“id为[“+id+”]-位置[“+Position+”]-行星[“+clickedView.getText()+”]),Toast.LENGTH_SHORT.show();
如果(id==0)
{
setContentView(R.layout.activity\u设置);
}
如果(id==1)
{
setContentView(R.layout.activity_about);
}
如果(id==2)
{
setContentView(R.layout.activity_反馈);
}
}
});
}
公共void onClickSend(视图五){
意向i=新意向(意向.行动\发送);
i、 setType(“消息/rfc822”);
i、 putExtra(Intent.EXTRA_电子邮件,新字符串[]{”matthew@calapai.com"});
i、 putExtra(Intent.EXTRA_SUBJECT,SUBJECT.getText().toString());
i、 putExtra(Intent.EXTRA_TEXT,mMessage.getText().toString());
试一试{
startActivity(Intent.createChooser(i,“发送邮件…”);
}捕获(android.content.ActivityNotFoundException ex){
Toast.makeText(MainActivity.this,“没有安装电子邮件客户端。”,Toast.LENGTH_SHORT.show();
}
}
//从这里
私有ServiceConnection myConnection=新ServiceConnection(){
ServiceConnected上的公共无效(ComponentName类名称,
IBinder服务){
BoundService.MyLocalBinder绑定器=(BoundService.MyLocalBinder)服务;
myService=binder.getService();
isBound=true;
}
ServiceDisconnected上的公共无效(组件名称arg0){
isBound=false;
}
};
//到这里
公共无效显示时间(查看)
{
myService.getCurrentTime();
}
/************************************************************************
*当用户打开和关闭家庭监听时
*它将启动服务并停止服务
*************************************************************************/
/*已勾选公共空间(视图){
布尔on=((ToggleButton)视图).isChecked();
如果(打开){
//Toast.makeText(MainActivity.this,“在主页打开的情况下激活Xecta”,Toast.LENGTH_LONG.show();
//startService(新的意图(getBaseContext(),Service1.class));
}否则{
//Toast.makeText(MainActivity.this,“在关闭主页的情况下激活Xecta”,Toast.LENGTH_LONG.show();
//stopService(新意图(getBaseContext(),LocalService.class));
}
}*/
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(R.menu.main,menu);
返回true;
}
/*公共void onclick服务(视图)
{
if(应用程序入口背景(上下文))
{
***
}
}*/
/**************************************************************************
*当用户按下HOME(主页)按钮时
******
package com.NautGames.xectav2.app;

import {...}

public class MainActivity extends ASR {

private ToggleButton homeOnOff;
HomeHoldDown hhd = new HomeHoldDown();

int keyCode;
KeyEvent event;

Context context;

private static final String LOGTAG = "Xecta";
private static final String BOTID = "e38006d97e34053e";

private TTS myTts;
private ImageButton speakButton;
private Bot bot;
Button backB1;
Button backB2;
Button backB3;

boolean mBound = false;

SimpleAdapter simpleAdpt;

BoundService myService = new BoundService();
boolean isBound = false;

EditText name, email, mMessage, subject;

String key;
String Name;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Intent intent = new Intent(this, BoundService.class);
    bindService(intent, myConnection, Context.BIND_AUTO_CREATE);

    //homeOnOff = (ToggleButton) findViewById(R.id.toggleButton);

    name = (EditText) findViewById(R.id.etName);
    email = (EditText) findViewById(R.id.etEmail);
    mMessage = (EditText) findViewById(R.id.etAdd);
    subject = (EditText) findViewById(R.id.txtSubject);

    Button startBtn = (Button) findViewById(R.id.send);

    backB1 = (Button)findViewById(R.id.button1);
    backB2 = (Button)findViewById(R.id.button2);
    backB3 = (Button)findViewById(R.id.button3);

    //Initialize GUI elements
    setSpeakButton();

    //Initialize the speech recognizer
    createRecognizer(getApplicationContext());

    //Initialize text to speech
    myTts = TTS.getInstance(this);

    //Create bot
    bot = new Bot(this, BOTID, myTts, "assistant");

    initList();

    // We get the ListView component from the layout
    ListView lv = (ListView) findViewById(R.id.listView);


    // This is a simple adapter that accepts as parameter
    // Context
    // Data list
    // The row layout that is used during the row creation
    // The keys used to retrieve the data
    // The View id used to show the data. The key number and the view id must match
    simpleAdpt = new SimpleAdapter(this, planetsList, android.R.layout.simple_list_item_1, new String[] {"page"}, new int[] {android.R.id.text1});


    lv.setAdapter(simpleAdpt);

    // React to user clicks on item
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {

        public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
                                long id)
        {
            // We know the View is a TextView so we can cast it
            TextView clickedView = (TextView) view;

            //Toast.makeText(MainActivity.this, "Item with id ["+id+"] - Position ["+position+"] - Planet ["+clickedView.getText()+"]", Toast.LENGTH_SHORT).show();
            if(id == 0)
            {
                setContentView(R.layout.activity_settings);
            }

            if(id == 1)
            {
                setContentView(R.layout.activity_about);
            }

            if(id == 2)
            {
                setContentView(R.layout.activity_feedback);
            }

        }
    });
}

public void onClickSend(View v) {

    Intent i = new Intent(Intent.ACTION_SEND);
    i.setType("message/rfc822");
    i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"matthew@calapai.com"});
    i.putExtra(Intent.EXTRA_SUBJECT, subject.getText().toString());
    i.putExtra(Intent.EXTRA_TEXT   , mMessage.getText().toString());
    try {
        startActivity(Intent.createChooser(i, "Send mail..."));
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(MainActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
    }

}

//from here
private ServiceConnection myConnection = new ServiceConnection() {

    public void onServiceConnected(ComponentName className,
                                   IBinder service) {
        BoundService.MyLocalBinder binder = (BoundService.MyLocalBinder) service;
        myService = binder.getService();
        isBound = true;
    }

    public void onServiceDisconnected(ComponentName arg0) {
        isBound = false;
    }

};
//to HERE

public void showTime(View view)
{
    myService.getCurrentTime();
}


/************************************************************************
 * WHEN THE USER TURNS THE HOME LISTENING ON AND OFF
 * IT WILL START SERVICE AND STOP SERVICE
 *************************************************************************/
/*public void onToggleClicked(View view) {
    boolean on = ((ToggleButton) view).isChecked();
    if (on) {
        //Toast.makeText(MainActivity.this, "Activate Xecta with Home ON", Toast.LENGTH_LONG).show();
        //startService(new Intent(getBaseContext(), Service1.class));
    } else {
        //Toast.makeText(MainActivity.this, "Activate Xecta with Home OFF", Toast.LENGTH_LONG).show();
        //stopService(new Intent(getBaseContext(), LocalService.class));
    }
}*/

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

/*public void onClickService(View view)
{
    if(isApplicationSentToBackground(context))
    {
        hhd.onKeyLongPress(keyCode, event);
    }
}*/

/**************************************************************************
 * WHEN THE USER HOLDS DOWN THE HOME BUTTON
 *************************************************************************/
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        Toast.makeText(MainActivity.this, "Key pressed long!", Toast.LENGTH_LONG).show();
        return true;
    }
    return super.onKeyLongPress(keyCode, event);
}

public void onClickBack(View view)
{
    setContentView(R.layout.activity_main);

}

// The data to show
List<Map<String, String>> planetsList = new ArrayList<Map<String,String>>();

private void initList() {
    // We populate the planets

    planetsList.add(newList("page", "Settings"));
    planetsList.add(newList("page", "About"));
    planetsList.add(newList("page", "FeedBack"));

}

private HashMap<String, String> newList(String key, String name) {
    HashMap<String, String> planet = new HashMap<String, String>();
    planet.put(key, name);

    return planet;
}

public void onClick(View view)
{
    speakButton = (ImageButton) findViewById(R.id.speech_btn);

    try {
        listen(RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH, 10);
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(),"ASR could not be started: invalid params", Toast.LENGTH_SHORT).show();
        Log.e(LOGTAG, e.getMessage());
    }
}

private void setSpeakButton() {
    speakButton = (ImageButton) findViewById(R.id.speech_btn);
    speakButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                listen(RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH, 10);
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "ASR could not be started: invalid params", Toast.LENGTH_SHORT).show();
                Log.e(LOGTAG, e.getMessage());
            }
        }
    });
}

/**
 * Provides feedback to the user when the ASR encounters an error
 */
public void processAsrError(int errorCode) {

    String errorMessage;
    switch (errorCode)
    {
        case SpeechRecognizer.ERROR_AUDIO:
            errorMessage = "Audio recording error";
            break;
        case SpeechRecognizer.ERROR_CLIENT:
            errorMessage = "Client side error";
            break;
        case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
            errorMessage = "Insufficient permissions" ;
            break;
        case SpeechRecognizer.ERROR_NETWORK:
            errorMessage = "Network related error" ;
            break;
        case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
            errorMessage = "Network operation timeout";
            break;
        case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
            errorMessage = "RecognitionServiceBusy" ;
            break;
        case SpeechRecognizer.ERROR_SERVER:
            errorMessage = "Server sends error status";
            break;
        case SpeechRecognizer.ERROR_NO_MATCH:
            errorMessage = "No matching message" ;
            break;
        case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
            errorMessage = "Input not audible";
            break;
        default:
            errorMessage = "ASR error";
            break;
    }

    try {
        myTts.speak(errorMessage,"EN");
    } catch (Exception e) {
        Log.e(LOGTAG, "English not available for TTS, default language used instead");
    }

    //If there is an error, shows feedback to the user and writes it in the log
    Log.e(LOGTAG, "Error: "+ errorMessage);
    Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}

public void processAsrReadyForSpeech() {
    Toast.makeText(this, "I'm listening", Toast.LENGTH_LONG).show();

}

public void processAsrResults(ArrayList<String> nBestList, float[] confidences) {
    String bestResult = nBestList.get(0);
    Log.d(LOGTAG, "Speech input: " + bestResult);
    // insert %20 for spaces in query
    bestResult = bestResult.replaceAll(" ", "%20");

    bot.initiateQuery(bestResult);

    //Toast.makeText(MainActivity.this, "", Toast.LENGTH_LONG).show();
}

@Override
public void onDestroy() {
    myTts.shutdown();
    super.onDestroy();
}

@Override
public void onBackPressed() {
    super.onBackPressed();
    setContentView(R.layout.activity_main);
    newList(key, Name);
    initList();
}

@Override
public void onStop()
{
    super.onStop();
    Toast.makeText(MainActivity.this, "Bye bye!", Toast.LENGTH_SHORT).show();
    onKeyLongPress(keyCode, event);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/onericblur"
android:orientation="vertical"
android:paddingBottom="5dp"
android:onClick="onClick"
android:weightSum="1">

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#000000"
    android:orientation="vertical" >

 <TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:background="#000000"
    android:paddingBottom="10dip"
    android:paddingTop="10dip"
    android:text="@string/title"
    android:textColor="#FFFFFF"
    android:textSize="18sp" />

 </LinearLayout>

<ViewAnimator
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/viewAnimator"
    android:layout_gravity="right" />

<ImageButton
    android:id="@+id/speech_btn"
    android:background="@null"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/xectaicon"
    android:onClick="onClick"
    android:layout_marginTop="32dp"
    android:layout_gravity="center_horizontal|top" />

<ListView
    android:layout_width="match_parent"
    android:layout_height="127dp"
    android:id="@+id/listView"
    android:layout_weight="1.22"
    android:background="@android:drawable/screen_background_light_transparent" />

</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1"
android:background="@drawable/onericblur">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    style="?android:attr/listSeparatorTextViewStyle"
    android:text="Settings"
    android:id="@+id/textView"
    android:layout_gravity="center_horizontal"
    android:textSize="30dp"
    android:textColor="@android:color/black" />

<TextView
    android:layout_width="291dp"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="Xecta is currently in Beta being tested, you can request settings by going to the feedback section. Sorry!"
    android:id="@+id/textView2"
    android:layout_weight="0.04"
    android:layout_gravity="center_horizontal"
    android:textSize="20dp"
    android:gravity="center|top" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Back to home"
    android:id="@+id/button3"
    android:onClick="onClickBack"
    android:layout_gravity="center_horizontal" />

</LinearLayout>
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ListView lv = (ListView) findviewById(R.id.list);

lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
    public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
                            long id)
    {

        Intent n = new Intent(getApplicationContext(),SettingsActivity.class);
        startActivity(n);
    }
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Buttoon btn = (Button) findviewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {
        Intent n = new Intent(getApplicationContext(),MainActivity.class);
        startActivity(n);
         }
     });
@Override
public void onResume()
{
    super.onResume();
 setContentView(R.layout.activity_main);
    Intent intent = new Intent(this, BoundService.class);
    bindService(intent, myConnection, Context.BIND_AUTO_CREATE);

    //homeOnOff = (ToggleButton) findViewById(R.id.toggleButton);

    name = (EditText) findViewById(R.id.etName);
    email = (EditText) findViewById(R.id.etEmail);
    mMessage = (EditText) findViewById(R.id.etAdd);
    subject = (EditText) findViewById(R.id.txtSubject);

    Button startBtn = (Button) findViewById(R.id.send);

    backB1 = (Button)findViewById(R.id.button1);
    backB2 = (Button)findViewById(R.id.button2);
    backB3 = (Button)findViewById(R.id.button3);

    //Initialize GUI elements
    setSpeakButton();

    //Initialize the speech recognizer
    createRecognizer(getApplicationContext());

    //Initialize text to speech
    myTts = TTS.getInstance(this);

    //Create bot
    bot = new Bot(this, BOTID, myTts, "assistant");

    initList();

    // We get the ListView component from the layout
    ListView lv = (ListView) findViewById(R.id.listView);


    // This is a simple adapter that accepts as parameter
    // Context
    // Data list
    // The row layout that is used during the row creation
    // The keys used to retrieve the data
    // The View id used to show the data. The key number and the view id must match
    simpleAdpt = new SimpleAdapter(this, planetsList, android.R.layout.simple_list_item_1, new String[] {"page"}, new int[] {android.R.id.text1});


    lv.setAdapter(simpleAdpt);

}
public void onClickBack(View view)
{
    setContentView(R.layout.activity_main);
    ListView lv = (ListView) findViewById(R.id.listView);
    lv.setAdapter(simpleAdpt);

}