我正在開發應用程序,其中我想在列表視圖中顯示一些引號和語錄,並且還希望在用戶單擊列表項目時在新佈局文件中顯示每個引號。這對我的主要活動代碼簡單列表視圖: -如何在新佈局中顯示Android ListView項目點擊
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* Created by Tauseef on 11/11/2015.
*/
public class MainActivity extends AppCompatActivity {
private String[] loveArray = {
"Jo Pyar Hamesha Sath Rahe Wo Sacha Hai Ji,\n" +
"Jo Musibaton Mein Kaam Aaye Wo Acha Hai Ji,\n" +
"Kabhi Kabhi Humse Bhi Ho Jati Hai Nadaniya,\n" +
"Kyonki Dil To Baccha Hai Ji.", "Chor to sakta hu,\n" +
"Magar Chor nahipate use,\n" +
"Wo shaks meri bigri huyi,\n" +
"Aadat ki trha hai.",
"Ek shaam aati hai tumhari yaad lekar,\n" +
"Ek shaam jaati hai tumhari yaad dekar,\n" +
"Par hume intezaar hai us shaam ka,\n" +
"Jo aaye sirf tumhe saath lekar"
};
private ListView loveListView;
private ArrayAdapter arrayAdapter;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_love);
Intent intent = getIntent();
loveListView = (ListView) findViewById(R.id.loveList);
// this-The current activity context.
// Second param is the resource Id for list layout row item
// Third param is input array
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, loveArray);
loveListView.setAdapter(arrayAdapter);
loveListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent newIntent = new Intent(LoveActivity.this, MainContent.class);
newIntent.putExtra("loveArray", position);
startActivity(newIntent);
}
});
}
}
這裏是僅具有TextView的中,我要顯示的點擊列表項的TextView的新活動: -
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
/**
* Created by Tauseef on 11/11/2015.
*/
public class MainContent extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView =(TextView)findViewById(R.id.mainContentTextView);
Intent intent = getIntent();
String data = "";
if(intent!= null){
Bundle extras = intent.getExtras();
if(extras != null){
data = extras.getString("loveArray");
}
}
}
}
每當我運行這個應用程序,並點擊列表項目顯示空指針excetion和一些別的東西。我沒有得到這個代碼實際發生的錯誤。
嘗試創建接受的類空數組,並把從意向進來它的內容。我也發現類的命名似乎是一個問題.... Intent newIntent = new Intent(LoveActivity.this,MainContent.class);不應該是MainActivity.this,MainContent.Class ... – Owner
我已經嘗試過,但沒有工作 – Tauseef
如果你在意圖中給予的立場。在接收器類中,它只會獲得被點擊的Item的索引值。您需要傳遞ListView中的字符串。 – Owner