此代码适用于ListView
,可在每个列表项中提供问题及其答案。我已经为 SHOW ANSWER 添加了一个按钮。当我点击第一项的 SHOW ANSWER 时,它显示第一项,第4项,第7项,第10项&的答案。等等。
我的Aptitude.java
public class Aptitude extends AppCompatActivity {
private String TAG = Aptitude.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
boolean first = true;
// URL to get questions
private int offset = 0;
private int limit = 10;
private int faq = 2;
private String url = "xyz/gk_app/qa.php/?faq="+ faq + "&offset=" + offset + "&limit=" + limit;
String ques, optn_a, optn_b, optn_c, optn_d, correct_optn;
View loading_footer;
private int preLast;
Boolean flag = false;
Aptitude_Custom_Adapter adapter;
private ArrayList<String> array_questions = new ArrayList<String>();
private ArrayList<String> array_correct_answer = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aptitude);
lv = (ListView) findViewById(R.id.listView_aptitude);
loading_footer = lv.inflate(Aptitude.this, R.layout.loading_footer, null);
lv.removeFooterView(loading_footer);
new GetQuestions().execute();
lv.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView absListView, int i) {
}
@Override
public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
final int lastItem = firstVisibleItem + visibleItemCount;
if(lastItem == totalItemCount) {
if(preLast!=lastItem && flag == true) {
lv.addFooterView(loading_footer);
flag = false;
new GetQuestions().execute();
preLast=lastItem;
}
}
}
});
android.support.v7.app.ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
private class GetQuestions extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Aptitude.this);
pDialog.setTitle("Loading question");
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... voids) {
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray questions = jsonObj.getJSONArray("questions");
url = jsonObj.getString("next_url");
// looping
for (int i = 0; i < questions.length(); i++) {
JSONObject c = questions.getJSONObject(i);
ques = c.getString("questions");
optn_a = c.getString("optn_a");
optn_b = c.getString("optn_b");
optn_c = c.getString("optn_c");
optn_d = c.getString("optn_d");
correct_optn = c.getString("correct_answer");
array_questions.add(ques);
array_correct_answer.add(chooseCorrectAnswer(optn_a, optn_b, optn_c, optn_d, correct_optn));
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
if(first == true) {
adapter = new Aptitude_Custom_Adapter(array_questions, array_correct_answer, getApplicationContext());
lv.setAdapter(adapter);
first = false;
} else {
int currentPosition = lv.getFirstVisiblePosition();
adapter.add(array_questions, array_correct_answer);
adapter.notifyDataSetChanged();
// Appending new data to menuItems ArrayList
// adapter = new Aptitude_Custom_Adapter(array_questions, array_correct_answer, getApplicationContext());
// lv.setAdapter(adapter);
// Setting new scroll position
lv.setSelectionFromTop(currentPosition + 1, 0);
}
lv.removeFooterView(loading_footer);
flag = true;
}
}
private String chooseCorrectAnswer( final String optn_a, final String optn_b, final String optn_c, final String optn_d, final String correct_optn) {
String correct_answer = null;
if(correct_optn.equals("optn_a")){
correct_answer = optn_a;
} if(correct_optn.equals("optn_b")){
correct_answer = optn_b;
} if(correct_optn.equals("optn_c")){
correct_answer = optn_c;
} if(correct_optn.equals("optn_d")){
correct_answer = optn_d;
}
return correct_answer;
}
@Override
public void onBackPressed() {
Intent intent = new Intent(Aptitude.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
array_questions.removeAll(array_questions);
array_correct_answer.removeAll(array_correct_answer);
startActivity(intent);
finish();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; goto parent activity.
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
适配器Aptitude_Custom_Adapter.java
public class Aptitude_Custom_Adapter extends BaseAdapter{
private Context activity;
private static LayoutInflater inflater=null;
public Resources res;;
private ArrayList<String> questionlist, correct_ans;
public Aptitude_Custom_Adapter(ArrayList<String> q, ArrayList<String> c, Context a) {
activity = a;
questionlist=q;
correct_ans=c;
System.out.println("in const: " + questionlist.size());
}
public void add(ArrayList<String> q, ArrayList<String> c){
questionlist.addAll(q);
correct_ans.addAll(c);
System.out.println("in add: " + questionlist.size());
}
@Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
@Override
public int getCount() {
if(questionlist.size()<=0)
return 1;
return questionlist.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
public static class ViewHolder{
public TextView ques_no, text_ques, text_ans;
public Button btn_ansr_show_hide;
public Boolean flag = true;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
if(convertView==null){
inflater = ( LayoutInflater )activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater.inflate(R.layout.aptitude_list_item, null);
holder = new ViewHolder();
holder.ques_no = (TextView) vi.findViewById(R.id.tv_ttp_ques_no);
holder.text_ques = (TextView) vi.findViewById(R.id.tv_ttp_question);
holder.text_ans = (TextView) vi.findViewById(R.id.tv_ttp_answer);
holder.btn_ansr_show_hide = (Button) vi.findViewById(R.id.btn_ansr_show_hide);
vi.setTag( holder );
} else
holder=(ViewHolder)vi.getTag();
if(questionlist.size()<=0){
holder.text_ques.setText("No Data");
holder.text_ans.setText("No Data");
holder.btn_ansr_show_hide.setText("");
} else {
holder.ques_no.setText("Question No. " + String.valueOf(position+1));
holder.text_ques.setText(questionlist.get(position).concat("?"));
holder.btn_ansr_show_hide.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
System.out.println("Position: "+position);
holder.btn_ansr_show_hide.setVisibility(View.GONE);
if (correct_ans.get(position).length() > 30){
holder.text_ans.setText(correct_ans.get(position).concat("."));
} else {
holder.text_ans.setText(correct_ans.get(position));
}
holder.flag = false;
}
});
if (holder.flag == false){
if (correct_ans.get(position).length() > 30){
holder.text_ans.setText(correct_ans.get(position).concat("."));
} else {
holder.text_ans.setText(correct_ans.get(position));
}
}
}
return vi;
}
}
主要布局activity_aptitude.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="@dimen/activity_margin"
android:background="@color/background"
tools:context=".Aptitude">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="2dp"
android:padding="8dp"
android:layout_marginBottom="10dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:gravity="center_vertical|center_horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Aptitude Questions"
android:id="@+id/to_aptitude"
android:textStyle="bold"
android:textColor="#ff6b6b"
android:layout_gravity="center"
android:gravity="center_vertical|center_horizontal" />
</LinearLayout>
</android.support.v7.widget.CardView>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
<ListView
android:id="@+id/listView_aptitude"
android:layout_width="fill_parent"
android:layout_height="match_parent" />
</LinearLayout>
</LinearLayout>
列表项布局aptitude_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/background">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="2dp"
android:padding="8dp"
android:layout_marginBottom="10dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="6dp"
android:gravity="center_vertical|center_horizontal"
android:background="#ffffff">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/layout_question">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Question: "
android:id="@+id/tv_ttp_ques_no"
android:textColor="#4a46c1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="This is a Sample question. This is a Sample question. This is a Sample question. This is a Sample question. "
android:id="@+id/tv_ttp_question"
android:textSize="20dp"
android:textColor="#272727" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:id="@+id/layout_answer">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Answer: "
android:id="@+id/tv_answer"
android:textColor="#4a46c1" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text=""
android:id="@+id/tv_ttp_answer"
android:textSize="20dp"
android:textColor="#272727" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Answer"
android:id="@+id/btn_ansr_show_hide"
android:background="@color/transparent"
android:textColor="@color/colorPrimary"
android:gravity="center_vertical|center_horizontal" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
答案 0 :(得分:0)
像这样创建一个名为Question
的类。
public class Question {
public String question;
public boolean answerShowed = false; // Make the attribute false by default
// Add a constructor
public void Question(String question, boolean answerShowed) {
this.question = question;
this. answerShowed = answerShowed;
}
}
现在选择ArrayList
private ArrayList<String> array_questions = new ArrayList<Question>();
在ArrayList
ques = c.getString("questions");
Question q = new Question(ques, false);
array_questions.add(q); // Add the object
现在您需要稍微修改适配器。首先,适配器的构造函数现在应该使用ArrayList
Question
对象。
private ArrayList<Question> questionlist;
public Aptitude_Custom_Adapter(ArrayList<Question> q, ArrayList<String> c, Context a) {
activity = a;
questionlist = q;
correct_ans = c;
System.out.println("in const: " + questionlist.size());
}
现在您需要相应地修改getView
和其他功能。从questionlist.get(position).question
获取问题字符串。
您在适配器中遗漏的棘手部分是在holder.btn_ansr_show_hide.setOnClickListener
功能之外设置可见性。另一方面,您需要提供if-else
条件来显示或消失 SHOW ANSWER 按钮。
所以你的getView
函数看起来应该是这样的。
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
if(convertView == null){
inflater = ( LayoutInflater )activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater.inflate(R.layout.aptitude_list_item, null);
holder = new ViewHolder();
holder.ques_no = (TextView) vi.findViewById(R.id.tv_ttp_ques_no);
holder.text_ques = (TextView) vi.findViewById(R.id.tv_ttp_question);
holder.text_ans = (TextView) vi.findViewById(R.id.tv_ttp_answer);
holder.btn_ansr_show_hide = (Button) vi.findViewById(R.id.btn_ansr_show_hide);
vi.setTag( holder );
} else
holder = (ViewHolder)vi.getTag();
holder.ques_no.setText("Question No. " + String.valueOf(position + 1));
holder.text_ques.setText(questionlist.get(position).question.concat("?"));
if (questionlist.get(position).answerShowed) {
holder.btn_ansr_show_hide.setVisibility(View.GONE);
holder.text_ans.setVisibility(View.VISIBLE);
if (correct_ans.get(position).length() > 30) holder.text_ans.setText(correct_ans.get(position).concat("."));
else holder.text_ans.setText(correct_ans.get(position));
} else {
holder.btn_ansr_show_hide.setVisibility(View.VISIBLE);
holder.text_ans.setVisibility(View.GONE);
}
holder.btn_ansr_show_hide.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!questionlist.get(position).answerShowed)
questionlist.get(position).answerShowed = true;
// Call notifyDataSetChanged here
notifyDataSetChanged();
}
});
return vi;
}