onItemClick不会在viewpager中打开所选项目
我有一个列表视图,使用带有helperclass的sqlite db填充
当我们点击listview中的某个项目时,它应该打开viewpager类,我们可以刷过各种细节
viewpager打开但始终从第一个列表项
开始即使我已经设置了
Bundle b = getIntent().getExtras();
int index = b.getInt("position");
mViewPager.setCurrentItem(index);
我想用我选择的项目打开viewpager,而不是每次都从第一个条目开始。
这里是listactivity
public class MyActivity extends Activity {
private CustomCursorAdapter customAdapter;
private PersonDatabaseHelper databaseHelper;
private static final int ENTER_DATA_REQUEST_CODE = 1;
private ListView listView;
private static final String TAG = MyActivity.class.getSimpleName();
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
databaseHelper = new PersonDatabaseHelper(this);
listView = (ListView) findViewById(R.id.list_data);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.d(TAG, "clicked on item: " + position);
Toast.makeText(getApplicationContext(), "aa" + position,
Toast.LENGTH_LONG).show();
//startActivity(new Intent(getApplicationContext(), viepagerActivity.class));
Intent i = new Intent(MyActivity.this, viepagerActivity.class);
i.putExtra("position", position);
MyActivity.this.startActivity(i);
}
});
new Handler().post(new Runnable() {
@Override
public void run() {
customAdapter = new CustomCursorAdapter(MyActivity.this,
databaseHelper.getAllData());
listView.setAdapter(customAdapter);
}
});
}
public void onClickEnterData(View btnAdd) {
startActivityForResult(new Intent(this, EnterDataActivity.class),
ENTER_DATA_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ENTER_DATA_REQUEST_CODE && resultCode == RESULT_OK) {
databaseHelper.insertData(
data.getExtras().getString("tag_person_name"), data
.getExtras().getString("tag_person_pin"));
customAdapter.changeCursor(databaseHelper.getAllData());
}
}
}
适配器
public class CustomCursorAdapter extends CursorAdapter {
public CustomCursorAdapter(Context context, Cursor c) {
super(context, c);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater
.inflate(R.layout.single_row_item, parent, false);
return retView;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
TextView textViewPersonName = (TextView) view
.findViewById(R.id.tv_person_name);
textViewPersonName.setText(cursor.getString(cursor
.getColumnIndex(cursor.getColumnName(1))));
TextView textViewPersonPIN = (TextView) view
.findViewById(R.id.tv_person_pin);
textViewPersonPIN.setText(cursor.getString(cursor.getColumnIndex(cursor
.getColumnName(2))));
}
}
viewpager
public class viepagerActivity extends Activity {
private List<String> testContactName = new ArrayList<String>();
private List<String> testContactNumber = new ArrayList<String>();
MyAdapter mAdapter;
private PersonDatabaseHelper databaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
databaseHelper = new PersonDatabaseHelper(this);
ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);
mAdapter = new MyAdapter();
mViewPager.setAdapter(mAdapter);
Bundle b = getIntent().getExtras();
int index = b.getInt("position");
mViewPager.setCurrentItem(index);
Toast.makeText(getApplicationContext(), "viepager" + index, Toast.LENGTH_LONG)
.show();
try {
getAllContacts();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void getAllContacts() {
SQLiteDatabase db = databaseHelper.database;
String[] columns = { PersonDatabaseHelper.PERSON_TABLE_COLUMN_ID,
PersonDatabaseHelper.PERSON_TABLE_COLUMN_NAME,
PersonDatabaseHelper.PERSON_TABLE_COLUMN_PIN, };
Cursor cursor = db.query(PersonDatabaseHelper.TABLE_NAME, columns,
null, null, null, null, null, null);
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(cursor
.getColumnName(1)));
String phoneNumber = cursor.getString(cursor.getColumnIndex(cursor
.getColumnName(2)));
testContactName.add(name);
mAdapter.notifyDataSetChanged();
testContactNumber.add(phoneNumber);
mAdapter.notifyDataSetChanged();
}
cursor.close();
}
private class MyAdapter extends PagerAdapter {
public MyAdapter() {
super();
}
@Override
public int getCount() {
return testContactName.size();
}
@Override
public boolean isViewFromObject(View collection, Object object) {
return collection == ((View) object);
}
@Override
public Object instantiateItem(View collection, int position) {
Bundle b = getIntent().getExtras();
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.viewpager_items, null);
TextView contactName = (TextView) view.findViewById(R.id.labelText);
TextView contactNumber = (TextView) view
.findViewById(R.id.answerText);
try {
contactName.setText(testContactName.get(position));
contactNumber.setText(testContactNumber.get(position));
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
((ViewPager) collection).addView(view, 0);
return view;
}
@Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((View) view);
mAdapter.notifyDataSetChanged();
}
}
}
助手类
public class PersonDatabaseHelper {
public static final String TAG = PersonDatabaseHelper.class
.getSimpleName();
// database configuration
// if you want the onUpgrade to run then change the database_version
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "mydatabase.db";
// table configuration
public static final String TABLE_NAME = "person_table"; // Table name
public static final String PERSON_TABLE_COLUMN_ID = "_id"; // a column
// named "_id"
// is required
// for cursor
public static final String PERSON_TABLE_COLUMN_NAME = "person_name";
public static final String PERSON_TABLE_COLUMN_PIN = "person_pin";
public DatabaseOpenHelper openHelper;
public SQLiteDatabase database;
// this is a wrapper class. that means, from outside world, anyone will
// communicate with PersonDatabaseHelper,
// but under the hood actually DatabaseOpenHelper class will perform
// database CRUD operations
public PersonDatabaseHelper(Context aContext) {
openHelper = new DatabaseOpenHelper(aContext);
database = openHelper.getWritableDatabase();
}
public void insertData(String aPersonName, String aPersonPin) {
// we are using ContentValues to avoid sql format errors
ContentValues contentValues = new ContentValues();
contentValues.put(PERSON_TABLE_COLUMN_NAME, aPersonName);
contentValues.put(PERSON_TABLE_COLUMN_PIN, aPersonPin);
database.insert(TABLE_NAME, null, contentValues);
}
public Cursor getAllData() {
String buildSQL = "SELECT * FROM " + TABLE_NAME;
Log.d(TAG, "getAllData SQL: " + buildSQL);
return database.rawQuery(buildSQL, null);
}
// this DatabaseOpenHelper class will actually be used to perform database
// related operation
private class DatabaseOpenHelper extends SQLiteOpenHelper {
public DatabaseOpenHelper(Context aContext) {
super(aContext, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
// Create your tables here
String buildSQL = "CREATE TABLE " + TABLE_NAME + "( "
+ PERSON_TABLE_COLUMN_ID + " INTEGER PRIMARY KEY, "
+ PERSON_TABLE_COLUMN_NAME + " TEXT, "
+ PERSON_TABLE_COLUMN_PIN + " TEXT )";
Log.d(TAG, "onCreate SQL: " + buildSQL);
sqLiteDatabase.execSQL(buildSQL);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion,
int newVersion) {
// Database schema upgrade code goes here
String buildSQL = "DROP TABLE IF EXISTS " + TABLE_NAME;
Log.d(TAG, "onUpgrade SQL: " + buildSQL);
sqLiteDatabase.execSQL(buildSQL); // drop previous table
onCreate(sqLiteDatabase); // create the table from the beginning
}
}
}