【发布时间】:2014-04-08 03:33:59
【问题描述】:
我正在使用片段和光标适配器来显示传入消息。对于每条消息,都有一个可以单击的按钮。我的 onclick 是在下面显示的底层活动中实现的。
public class ChatActivity extends FragmentActivity implements StatFragment.OnFragmentInteractionListener, ChatFragment.OnFragmentInteractionListener, EditContactDialog.OnFragmentInteractionListener {
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
profileId = getIntent().getStringExtra(Common.PROFILE_ID);
//msgEdit = (EditText) findViewById(R.id.msg_edit);
msgInvite_edit = (EditText) findViewById(R.id.msgInvite_edit);
buttonNewInvite = (Button) findViewById(R.id.buttonNewInvite);
buttonYES = (Button) findViewById(R.id.button1);
ans1 = getIntent().getIntExtra(DataProvider.COL_ANSCOUNT, 0);
//BAS: de zendknop voor het antwoorden op de Invite
sendBtn = (Button) findViewById(R.id.send_btn);
//checkBtn = (CheckBox) findViewById(R.id.checkBox1);
//buttonId = getIntent.getStringExtra(DataProvider.COL_ID);
//BAS: deze tabhost voeg ik toe voor de tabInvites en tabStats
TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
tabHost.setup();
ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
//BAS: dit hoort nog bij tabhost
TabHost.TabSpec tabSpec = tabHost.newTabSpec("Stats");
tabSpec.setContent(R.id.tabInvites);
tabSpec.setIndicator("Stats");
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("Chat");
tabSpec.setContent(R.id.tabStats);
tabSpec.setIndicator("Chat");
tabHost.addTab(tabSpec);
Cursor c = getContentResolver().query(Uri.withAppendedPath(DataProvider.CONTENT_URI_PROFILE, profileId), null, null, null, null);
if (c.moveToFirst()) {
profileName = c.getString(c.getColumnIndex(DataProvider.COL_NAME));
profileEmail = c.getString(c.getColumnIndex(DataProvider.COL_EMAIL));
actionBar.setTitle(profileName);
}
actionBar.setSubtitle("connecting ...");
registerReceiver(registrationStatusReceiver, new IntentFilter(Common.ACTION_REGISTER));
gcmUtil = new GcmUtil(getApplicationContext());
//BAS: hier zet ik de '+add invite' listener
buttonNewInvite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), AddInvite.class);
intent.putExtra(Common.PROFILE_ID, String.valueOf(profileId));
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.chat, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.msgInvite_edit: //action_edit CHANGE
EditContactDialog dialog = new EditContactDialog();
Bundle args = new Bundle();
args.putString(Common.PROFILE_ID, profileId);
args.putString(DataProvider.COL_NAME, profileName);
dialog.setArguments(args);
dialog.show(getFragmentManager(), "EditContactDialog");
return true;
case android.R.id.home:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
public void onClick(View v) {
switch(v.getId()) {
//BAS: dit is voor de terugstuur knop in de STATS!
// BAS: Dit is wanneer de send knop van het Addinvite scherm gebruikt wordt!
case R.id.buttonSendInvite:
send(msgInvite_edit.getText().toString(),null);
//Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show();
msgInvite_edit.setText(null); }
}
@Override
public void onEditContact(String name) {
getActionBar().setTitle(name);
}
//public void onListItemClick(ListView l, View v, int position, long id) {
// Toast.makeText(this,"onListItemClick position is" + position, Toast.LENGTH_LONG).show();
//showDetails(position);
//}
public void onYESClick(View v) {
int intID = v.getId();
switch(v.getId()) {
case R.id.button1:
Button buttonYES = (Button) findViewById(intID);
//Toast.makeText(this, profileName, Toast.LENGTH_SHORT).show();
//send(null, profileName);
//bas:sets to button to 0 everytime you reload it.
Cursor c = getContentResolver().query(DataProvider.CONTENT_URI_BUTTONS, null, null, null, null, null);
if( c != null && c.moveToFirst()){
//c.getPosition();
ans1 = c.getInt(c.getColumnIndex(DataProvider.COL_ANSCOUNT));
//System.out.println(ans1);
if(ans1 < 0){
ans1=0;
}
if (ans1 == 0){
id = c.getInt(0);
buttonYES.setPressed(true);
ans1++;
ContentValues values = new ContentValues(3);
values.put(DataProvider.COL_BTNTXT, buttonYES.getHint().toString());
values.put(DataProvider.COL_ANSFROM, profileName);
values.put(DataProvider.COL_ANSCOUNT, ans1);
this.getContentResolver().update(DataProvider.CONTENT_URI_BUTTONS, values, "_id = " + id, null);
}
else {
id = c.getInt(0);
buttonYES.setPressed(false);
ans1--;
ContentValues values = new ContentValues(3);
values.put(DataProvider.COL_BTNTXT, buttonYES.getHint().toString());
values.put(DataProvider.COL_ANSFROM, profileName);
values.put(DataProvider.COL_ANSCOUNT, ans1);
this.getContentResolver().update(DataProvider.CONTENT_URI_BUTTONS, values, "_id = " + id, null);
//}c.moveToNext();
}
}c.close();
}
}
@Override
public String getProfileEmail() {
return profileEmail;
}
@Override
protected void onPostExecute(String msg) {
if (!TextUtils.isEmpty(msg)) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
}
}.execute(null, null, null);
}
@Override
protected void onPause() {
ContentValues values = new ContentValues(1);
values.put(DataProvider.COL_COUNT, 0);
getContentResolver().update(Uri.withAppendedPath(DataProvider.CONTENT_URI_PROFILE, profileId), values, null, null);
super.onPause();
}
@Override
protected void onDestroy() {
unregisterReceiver(registrationStatusReceiver);
gcmUtil.cleanup();
super.onDestroy();
}
//--------------------------------------------------------------------------------
private BroadcastReceiver registrationStatusReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null && Common.ACTION_REGISTER.equals(intent.getAction())) {
switch (intent.getIntExtra(Common.EXTRA_STATUS, 100)) {
case Common.STATUS_SUCCESS:
getActionBar().setSubtitle("online");
sendBtn.setEnabled(true);
break;
case Common.STATUS_FAILED:
getActionBar().setSubtitle("offline");
break;
}
}
}
};
}
但此时光标只占据我在这种情况下用 c.moveToFirst() 给他的位置。我希望这个光标适应它被点击的按钮位置。因此,例如,如果我单击顶部的“是”按钮,我希望它对该项目产生影响,因此它需要根据正确的 column_id 移动到该行。从我读过的所有内容来看,这似乎是我需要在片段中实现的东西,但我的 onItemClick 和 Listeners 到目前为止还没有任何帮助。
看起来很像这样: How to Handle Button Clicks ListFragment 但我无法让它工作......如何为 cursoradapter 实现的每个文本气球设置一个位置?
public class StatFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor>, OnItemClickListener {
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener");
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
now = new Date();
//BAS: de TABLE_URI die gebruikt wordt voor de adapter staat onderaan deze pagina!!
adapter = new SimpleCursorAdapter(getActivity(),
R.layout.list_invite,
null,
new String[]{DataProvider.COL_QUESTION, DataProvider.COL_ANSFROM, DataProvider.COL_ANSCOUNT},
new int[]{R.id.text1, R.id.text2, R.id.text3},
0);
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
//BAS: goed om te weten, de viewbinder is dus degene die daadwerkelijk de string vult met
//de waarde die het vertegenwoordigt.LOL
//BAS: dit is het stukje waar de simplecursoradapter gebruikt wordt om het berichtje
// op te halen uit de database, namelijk COL_MSG/COL_AT en deze een id mee te geven, text1 en text2 en
// te plaatsen in het messagefragment
switch(view.getId()) {
case R.id.text1:
LinearLayout root = (LinearLayout) view.getParent().getParent();
//BAS: col_from means it is send by the other person so it comes 'from' someone
if (cursor.getString(cursor.getColumnIndex(DataProvider.COL_QUESTION)) == null ) {
} else {
}
break;
case R.id.text2:
TextView tv = (TextView) view;
tv.setText(cursor.getString(columnIndex));
break;
case R.id.text3:
TextView tv3 = (TextView) view;
tv3.setText(cursor.getString(columnIndex));
break;
//return true;
}
return false;
}
});
setListAdapter(adapter);
//BAS: geen listview aanroepen!! werkt niet goed ofzo..
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getListView().setDivider(null);
Bundle args = new Bundle();
args.putString(DataProvider.COL_EMAIL, mListener.getProfileEmail());
getLoaderManager().initLoader(0, args, this);
}
private OnClickListener mClickListener = new OnClickListener() {
public void onClick(View v) {
buttonYES.setOnClickListener(mClickListener);
buttonYES.setTag(1);
switch(v.getId())
{
case R.id.button1 :
// btn clicked
Toast.makeText(getActivity()," Button1 clicked at positon"+v.getTag(), Toast.LENGTH_SHORT).show();
break;
//case R.id.button_id2 :
// btn2 clicked
// Toast.makeText(context," Button2 clicked at positon"+v.getTag(), Toast.LENGTH_SHORT).show();
// break;
// case R.id.button_id3 :
// Toast.makeText(context," Button3 clicked at positon"+v.getTag(), Toast.LENGTH_SHORT).show();
// btn 3 clciked
// break;
}
}
};
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
public String getProfileEmail();
}
@SuppressWarnings("deprecation")
private String getDisplayTime(String datetime) {
try {
Date dt = sdf.parse(datetime);
if (now.getYear()==dt.getYear() && now.getMonth()==dt.getMonth() && now.getDate()==dt.getDate()) {
return df[1].format(dt);
}
return df[0].format(dt);
} catch (ParseException e) {
return datetime;
}
}
//----------------------------------------------------------------------------
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String profileEmail = args.getString(DataProvider.COL_EMAIL);
CursorLoader loader = new CursorLoader(getActivity(),
DataProvider.CONTENT_URI_BUTTONS,
null,
DataProvider.COL_QFROM + " = ? or " + DataProvider.COL_QTO + " = ?",
new String[]{profileEmail, profileEmail},
DataProvider.COL_AT + " DESC");
return loader;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
}
【问题讨论】:
标签: java android button fragment