gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 13:07:26 25 4
gpt4 key购买 nike

我的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;

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[]{"name@email.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);
}

}

onClickBack是返回activity_main.xml的按钮,我也在onCreate()中初始化ListView。

activity_main.xml

<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>

还有activity_settings...

<?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>

什么可能导致这个问题?!?!?

谢谢。

最佳答案

根据 Ram Kiran 的建议,最好为“设置”/“主页”设置不同的 Activity 。

您发布的代码的问题是,当您按回键时,您没有用内容填充列表。我相信应该使用以下代码修复它,

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

}

基本上,当您调用 setContentView(layoutId) 时,新 View 将从布局中膨胀,您需要再次进行所有 UI 查找和初始化。

关于java - Android - ListView 在 setContentView() 之后消失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23165917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com