My problem is that I duplicate the contents of the layout and I do not understand the reason.
I'm working with fragments and the code is as follows
fragment code
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/activity_crear_itinerario"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:name="com.example.pablo.p_final2.CrearItinerarioFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
java fragment
public class CrearItinerarioFragment extends Fragment{
private Button continuar;
private EditText pob, nomb;
private int flag1 = 0,flag2 = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_crear_itinerario, container, false);
pob = (EditText) view.findViewById(R.id.Poblacion);
nomb = (EditText) view.findViewById(R.id.Nombre);
continuar = (Button) view.findViewById(R.id.BotonContinuar);
pob.addTextChangedListener(new TextValidator(pob) {
#Override
public void validate(EditText editText, String text) {
//Implementamos la validaciĆ³n De campo vacio
if( text.length() <= 0 ) {
pob.setError(getString(R.string.CampoVacio));
flag1 = 0;
}
else
{
flag1 = 1;
}
}
});
nomb.addTextChangedListener(new TextValidator(nomb) {
#Override
public void validate(EditText editText, String text) {
//Implementamos la validaciĆ³n de campo vacio
if( text.length() <= 0 ) {
nomb.setError(getString(R.string.CampoVacio));
flag2 = 0;
}else
{
flag2 = 1;
}
}
});
continuar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(flag1!=1 || flag2 !=1)
{
Toast.makeText(CrearItinerarioFragment.this.getActivity(), getString(R.string.CamposVacios),Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(CrearItinerarioFragment.this.getActivity(), getString(R.string.ItinerarioCreado), Toast.LENGTH_LONG).show();
//Creamos el intent
Intent intent = new Intent(CrearItinerarioFragment.this.getActivity(), ControlarItinerarioActivity.class);
//Iniciamos la nueva actividad
startActivity(intent);
}
}
});
return view;
}
}
scrollview
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragment_hacer_foto">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/LblTitulo"
android:text="#string/TituloFoto"
android:layout_margin="15dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30dp"
android:gravity="center"/>
<EditText
android:id="#+id/Titulo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="15dp"
android:maxLength="30" />
<TextView
android:id="#+id/LblComentario"
android:text="#string/ComentarioFoto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30dp"
android:gravity="center"
android:layout_margin="15dp"/>
<EditText
android:id="#+id/Comentario"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="15dp"
android:maxLength="400"/>
<Button
android:id="#+id/BtnContinuar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="15dp"
android:text="#string/continuar"/>
</LinearLayout>
</ScrollView>
![1]: http://en.zimagez.com/zimage/photo1278635382500599725.php "correct"
![2]: http://en.zimagez.com/zimage/photo1278635382500599724.php "problem"
I want it to stay the same as in the first photo, but as soon as I click on one of the edittext or move the screen is set as the second
Thank you very much
if you are adding data in layout dynamically, then you need to remove all views and add them again
Can you please show code what you are doing in Fragment class where you adding views in framlayout
Related
I have an FragmentActivity which contain WebView, Edittext1, Edittext2, Checkboxes and button. When I click the button in fragment it will move to Results_activity. And if I click button from Results_activity it move back to FragmentActivity.
But my edittext values getting cleared while moving back.
FragmentActivity xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/background_light"
android:orientation="vertical">
<LinearLayout
android:id="#+id/questionContainer"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<WebView
android:id="#+id/questionWV"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<LinearLayout
android:id="#+id/ansA_container"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="5dp"
android:paddingTop="5dp"
android:paddingRight="5dp"
android:paddingBottom="5dp">
<EditText
android:id="#+id/ansA"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:freezesText="true"
android:hint="Enter answer here..."
android:minWidth="50dp"
android:minHeight="50dp"
android:scrollbars="vertical"
android:textAppearance="#android:style/TextAppearance.Medium" />
</LinearLayout>
<LinearLayout
android:id="#+id/ansB_container"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="5dp"
android:paddingTop="5dp"
android:paddingRight="5dp"
android:paddingBottom="5dp">
<EditText
android:id="#+id/ansB"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:freezesText="true"
android:hint="Enter answer here..."
android:minWidth="50dp"
android:minHeight="50dp"
android:scrollbars="vertical"
android:textAppearance="#android:style/TextAppearance.Medium" />
</LinearLayout>
<LinearLayout
android:id="#+id/answers_container"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="5dp"
android:paddingTop="5dp"
android:paddingRight="5dp"
android:paddingBottom="5dp">
<RelativeLayout
android:id="#+id/answer_a_container"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_gravity="top"
android:layout_weight="1">
<CheckBox
android:id="#+id/answerA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:hint="0"
android:maxLines="100"
android:minWidth="50dp"
android:minHeight="50dp"
android:scrollbars="vertical"
android:text="Varianta A"
android:textAppearance="#android:style/TextAppearance.Medium" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/answer_b_container"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<CheckBox
android:id="#+id/answerB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="false"
android:layout_marginStart="15dp"
android:hint="1"
android:maxLines="100"
android:minWidth="50dp"
android:minHeight="50dp"
android:scrollbars="vertical"
android:text="Varianta B"
android:textAppearance="#android:style/TextAppearance.Medium" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/answer_c_container"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<CheckBox
android:id="#+id/answerC"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:hint="2"
android:maxLines="100"
android:minWidth="50dp"
android:minHeight="50dp"
android:scrollbars="vertical"
android:text="Varianta C"
android:textAppearance="#android:style/TextAppearance.Medium" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/answer_d_container"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<CheckBox
android:id="#+id/answerD"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:hint="3"
android:maxLines="100"
android:minWidth="50dp"
android:minHeight="50dp"
android:scrollbars="vertical"
android:text="Varianta D"
android:textAppearance="#android:style/TextAppearance.Medium" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/footer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="bottom|center"
android:orientation="horizontal"
android:paddingBottom="30dp">
<Button
android:id="#+id/btnFinishTest"
style="#android:style/Widget.Button.Inset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/testbutton"
android:onClick="FinishTest"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="Finish Test" />
<Button
android:id="#+id/btnAnswer"
style="#android:style/Widget.Button.Inset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/testbutton"
android:onClick="SubmitAnswer"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="Submit Answer" />
</LinearLayout>
</LinearLayout>
Fragment Code
my edittexts are et1 and et2
public class QuestionFragment2018ii extends Fragment {
LinearLayout answersContainer;
int currentPageNr;
private String input1;
#Override
public View onCreateView(LayoutInflater lInflater, ViewGroup container,Bundle saveInstanceState){
currentPageNr = getArguments().getInt("position");
//initialize some variables
final Question2018ii currentQuestion2018ii = MyServerData2018ii.getInstance().getQuestion(currentPageNr);
View rootView = lInflater.inflate(R.layout.quiz_activity_fragment,container,false);
//initialize show answer option
final String ans = currentQuestion2018ii.getExplanationText();
final EditText et1 = rootView.findViewById(R.id.ansA);
final EditText et2 = rootView.findViewById(R.id.ansB);
if(MyServerData2018ii.getInstance().getTestState().equals("finished") ){
et1.setText("Your Response: " + et.getText());
et2.setText("Correct Answer: " + ans);
}
//initialize Explanation option
//initialize answers
answersContainer = (LinearLayout)rootView.findViewById(R.id.answers_container);
String[] answers = currentQuestion2018ii.getAllAnswersText();
for (int i = 0; i < answersContainer.getChildCount(); i++) {
RelativeLayout checkboxContainer = (RelativeLayout)answersContainer.getChildAt(i);
CheckBox cb = (CheckBox)checkboxContainer.getChildAt(0);
cb.setMovementMethod(new ScrollingMovementMethod());
cb.setText(answers[i]);
cb.setChecked(currentQuestion2018ii.isChecked(i));
if(MyServerData2018ii.getInstance().getTestState().equals("finished") ){
cb.setEnabled(false);
questionWebView.loadUrl("file:///android_asset/" + currentQuestion2018ii.getSolutionText());
//check if answer is right or wrong
if(currentQuestion2018ii.isCorrectAnswer(i)){
cb.setTextColor(Color.parseColor("#4DAD47"));
cb.setTypeface(null, Typeface.BOLD);
} else {
cb.setTextColor(Color.parseColor("#CE0B0B"));
}
}else{
cb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = ((CheckBox) v);
int number = Integer.parseInt(cb.getHint().toString());
currentQuestion2018ii.setChecked(number, cb.isChecked());
}
});
}
}
return rootView;
}
}
ResultsActivity xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:paddingBottom="10dp"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:paddingTop="30dp"
android:text="#string/results"
android:textColor="#4DAD47"
android:textSize="20sp"
android:textStyle="bold|italic" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:paddingTop="30dp" >
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<TextView
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:paddingBottom="20dp"
android:text="#string/correct_answers" />
</LinearLayout>
<TextView
android:id="#+id/myTotalAnswers"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center_vertical|center_horizontal"
android:paddingRight="5dp"
android:text="50/100" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/mainContainer"></LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal">
<Button
android:id="#+id/check_results"
style="#android:style/Widget.Button.Inset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:background="#drawable/testbutton"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/check_results" />
<Button
android:id="#+id/btnMainMenu"
style="#android:style/Widget.Button.Inset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:background="#drawable/testbutton"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/main_menu" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</ScrollView>
Quiz activity
public class QuizActivity2018ii extends AppCompatActivity {
Spinner spinCategory;
EditText questionNr;
ArrayList<String> allCategories;
int totalQuestions;
AlertDialog dialog;
ViewPager pager;
QuestionPagerAdapter2018ii pagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.quiz_activity_view_pager);
allCategories = new ArrayList<>(MyServerData2018ii.getInstance().getCategoryList());
totalQuestions = MyServerData2018ii.getInstance().getTotalQuestions();
//initialize category spinner
ArrayAdapter<String> categoryAdapter = new ArrayAdapter<>(this,android.R.layout.simple_spinner_dropdown_item,allCategories);
spinCategory = (Spinner) findViewById(R.id.category);
spinCategory.setAdapter(categoryAdapter);
spinCategory.setSelection(0);
//set Category spinner callback
spinCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String currentQuestionRealCategory = MyServerData2018ii.getInstance().getQuestionCategory(pager.getCurrentItem());
String selectedCategory = spinCategory.getItemAtPosition(position).toString();
if (!selectedCategory.equals(currentQuestionRealCategory)) {
int firstQuestionNumberFromCategory = MyServerData2018ii.getInstance().getFirstQuestionNumberFromCategory(selectedCategory);
ViewPager pager = (ViewPager) findViewById(R.id.qPager);
pager.setCurrentItem(firstQuestionNumberFromCategory, false);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//initialize number
questionNr = (EditText) findViewById(R.id.dialog_question_number);
questionNr.clearFocus();
//set number callbacks
questionNr.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_ENTER)) {
v.clearFocus();
CharSequence s = questionNr.getText();
if (!s.toString().isEmpty()) {
Integer questionNumber = Integer.parseInt(s.toString());
//avoids out of range indexes
if (questionNumber > totalQuestions + 1) {
questionNumber = totalQuestions;
}
if (questionNumber < 0) {
questionNumber = 1;
}
//create looping effect
if (questionNumber == totalQuestions + 1) {
questionNumber = 1;
((EditText)v).setText("1");
}
if (questionNumber == 0) {
questionNumber = totalQuestions;
((EditText)v).setText(String.valueOf(totalQuestions));
}
ViewPager pager = (ViewPager) findViewById(R.id.qPager);
pager.setCurrentItem(questionNumber, false);
questionNr.clearFocus();
} else {
questionNr.setText("1");
}
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
return false;
}
});
//initialize pager
pager = (ViewPager)findViewById(R.id.qPager);
pagerAdapter = new QuestionPagerAdapter2018ii(getSupportFragmentManager());
pager.setAdapter(pagerAdapter);
pager.setCurrentItem(1, false);
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
#Override
public void onPageSelected(int position) {
Integer currentQuestion = pager.getCurrentItem();
//change spinner
String currentCategory = MyServerData2018ii.getInstance().getQuestionCategory(currentQuestion);
int categoryPosition = MyServerData2018ii.getInstance().getCategoryList().indexOf(currentCategory);
spinCategory.setSelection(categoryPosition);
//change numberPicker
if(currentQuestion <= 0){currentQuestion = totalQuestions;}
if(currentQuestion > totalQuestions){currentQuestion = 1;}
questionNr.setText(currentQuestion.toString());
questionNr.clearFocus();
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(questionNr.getWindowToken(), 0);
}
#Override
public void onPageScrollStateChanged(int state) {
int totalQuestions = MyServerData2018ii.getInstance().getTotalQuestions();
if (state == ViewPager.SCROLL_STATE_IDLE) {
if (pager.getCurrentItem() == totalQuestions + 1) {
pager.setCurrentItem(1, false);
}
if (pager.getCurrentItem() == 0) {
pager.setCurrentItem(totalQuestions, false); // false will prevent sliding animation of view pager
}
}
}
});
}
public void FinishTest(View v){
//check if there are unanswered questions
if(MyServerData2018ii.getInstance().getTestState().equals("inProgress")){
ArrayList<String> UnansweredQuestions = new ArrayList<>();
LinkedHashMap<String,Object> allQuestions = MyServerData2018ii.getInstance().getAllQuestions();
for(Map.Entry category: allQuestions.entrySet()){
Question2018ii[] question2018iis = (Question2018ii[])category.getValue();
for(int i = 0; i < question2018iis.length; i++){
Boolean[] userAnswers = question2018iis[i].getUserAnswers();
if(!Arrays.asList(userAnswers).contains(true)){
String checkedCategory = (String)category.getKey();
Integer questionNumberInList = MyServerData2018ii.getInstance().getQuestionListNumber(checkedCategory,i);
UnansweredQuestions.add(String.valueOf(questionNumberInList));
}
}
}
if(UnansweredQuestions.size() > 0){
dialog = new AlertDialog.Builder(this)
.create();
LayoutInflater infl = LayoutInflater.from(this);
dialog.setView(infl.inflate(R.layout.dialog_message,null));
dialog.show();
TextView message = (TextView)dialog.findViewById(R.id.message);
String unfinished = getResources().getString(R.string.unfinished_text);
String questions = TextUtils.join(",",UnansweredQuestions);
message.setText(unfinished + "\n" + questions + ".");
dialog.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.findViewById(R.id.btn_ok).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
showResults();
}
});
}else{showResults();}
}else{
showResults();
}
}
public void showResults(){
int animationDuration;
if(MyServerData2018ii.getInstance().getTestState().equals("finished")){
animationDuration = 10;
}else{
animationDuration = 2000;
}
View mainView = LayoutInflater.from(this).inflate(R.layout.quiz_activity_show_results,null);
LinearLayout mainContainer = (LinearLayout)mainView.findViewById(R.id.mainContainer);
mainView.findViewById(R.id.btnMainMenu).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//finish the test and go to main menu
Intent Main = new Intent(getApplicationContext(),MainActivity.class);
finish();
startActivity(Main);
MyServerData2018ii.getInstance().setTestState("notStarted");
MyServerData2018ii.getInstance().clearAnswers();
Toast.makeText(getBaseContext(),R.string.text_ended,Toast.LENGTH_LONG).show();
}
});
mainView.findViewById(R.id.check_results).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
Question2018ii[] currentCategory;
int totalCategoryQuestions;
int correctCategoryQuestions;
int totalCorrectQuestions = 0;
//checking and adding each category
for(String category: allCategories){
View categoryContainer = LayoutInflater.from(this).inflate(R.layout.quiz_activity_category_results,null);
TextView categoryName = (TextView)categoryContainer.findViewById(R.id.categoryName);
//set name
categoryName.setText(category);
currentCategory = MyServerData2018ii.getInstance().getCategory(category);
totalCategoryQuestions = currentCategory.length;
//check answers
correctCategoryQuestions = 0;
for(int i=0; i < currentCategory.length;i++){
Boolean isCorrect = Arrays.equals(currentCategory[i].getAllCorrectAnswers(),currentCategory[i].getUserAnswers());
if(isCorrect){ correctCategoryQuestions++;}
}
totalCorrectQuestions += correctCategoryQuestions;
//set results
String result = String.valueOf(correctCategoryQuestions) + "/" + String.valueOf(totalCategoryQuestions);
final ProgressBar progress = (ProgressBar)categoryContainer.findViewById(R.id.progressBar);
progress.setMax(totalCategoryQuestions*100);
final TextView myResult = (TextView)categoryContainer.findViewById(R.id.categoryResult);
final String myResultText = "/" + String.valueOf(totalCategoryQuestions);
ValueAnimator val = new ValueAnimator();
val.setObjectValues(0, correctCategoryQuestions*100);
val.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
myResult.setText(String.valueOf((Integer)animation.getAnimatedValue()/100) + myResultText);
progress.setProgress( ((Integer) animation.getAnimatedValue()));
}
});
val.setDuration(animationDuration);
val.start();
mainContainer.addView(categoryContainer);
}
//animate results
final TextView tvTotalResult =(TextView)mainView.findViewById(R.id.myTotalAnswers);
final String totalResultS = "/" + String.valueOf(totalQuestions);
ValueAnimator totalResultsAnimator = new ValueAnimator();
totalResultsAnimator.setObjectValues(0, totalCorrectQuestions);
totalResultsAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
tvTotalResult.setText(String.valueOf(animation.getAnimatedValue()) + totalResultS);
}
});
totalResultsAnimator.setDuration(animationDuration);
totalResultsAnimator.start();
MyServerData2018ii.getInstance().setTestState("finished");
setContentView(mainView);
}
}
this is my question yearwise activity(from this I launched the fragment activity)
public class QuestionYearwise extends AppCompatActivity{
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.question_yearwise);
Button btn2018ii = (Button)findViewById(R.id.btn2018ii);
btn2018ii.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent Quiz2018ii = new Intent(getApplicationContext(),QuizActivity2018ii.class);
MyServerData2018ii.getInstance().setTestState("inProgress");
startActivity(Quiz2018ii);
}
});
}
}
Replace the method like this,
mainView.findViewById(R.id.check_results).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
i am creating an application, which i use to create a list of things that i have in SQLite database
i created a Fragment with a button that add a xml file to my LinearLayout , it works good , but i want to grab EditText and Spinner data and put them in a JSONobject but i don't know how , i don't have IDs of dynamically created views
My Fragment XML
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/itemsContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="50dp"
android:orientation="vertical"
android:paddingTop="20dp">
</LinearLayout>
</ScrollView>
<android.support.design.widget.FloatingActionButton
android:id="#+id/addItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_margin="16dp"
app:srcCompat="#drawable/fab_add"
/>
</RelativeLayout>
My field (addView) XML
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
android:weightSum="3"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:weightSum="2">
<Button
android:id="#+id/add"
android:onClick="onIncrease"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="center"
android:background="#drawable/ic_add_circle_black_24dp" />
<Button
android:id="#+id/remove"
android:onClick="onDecrease"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:background="#drawable/ic_remove_circle_black_24dp" />
</LinearLayout>
<EditText
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:inputType="number"
android:hint="#string/number"
/>
<Spinner
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
Fragment.java File
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_newfactor,container,false);
fab = v.findViewById(R.id.addItem);
ln = v.findViewById(R.id.itemsContainer);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.field, null);
final EditText editText = rowView.findViewById(R.id.number);
Button add = rowView.findViewById(R.id.add);
Button remove = rowView.findViewById(R.id.remove);
Button clear = rowView.findViewById(R.id.clear);
Spinner spinner = rowView.findViewById(R.id.spinner);
list = new ArrayList<>();
dbConnector = new DbConnector(getContext(),null,null,1);
Cursor c = dbConnector.get().rawQuery("SELECT * FROM product",null);
while (c.moveToNext()){
int id = c.getInt(c.getColumnIndex("id"));
String name = c.getString(c.getColumnIndex("name"));
String desc = c.getString(c.getColumnIndex("description"));
String price = c.getString(c.getColumnIndex("price"));
list.add(new SpinnerObject(id,name,price));
}
spinnerAdapter = new ir.animelist.localshop.Adaptors.SpinnerAdapter(getContext(),android.R.layout.simple_list_item_1,list);
spinner.setAdapter(spinnerAdapter);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int num = Integer.parseInt(editText.getText().toString());
int num_num = num + 1;
editText.setText(num_num + "");
}
});
remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int num = Integer.parseInt(editText.getText().toString());
if(num > 0){
int num_num = num - 1;
editText.setText(num_num + "");
}
}
});
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ln.removeView((View) v.getParent());
}
});
ln.addView(rowView, ln.getChildCount() - 1);
}
});
return v;
}
You need to use the recyclerview to display your list items. Using recyclerview you can get view like -
View view = recyclerview.findViewHolderForAdapterPosition(pos).itemView;
Spinner spinner = view.findViewById(R.id.mySpinner);
This will return you a spinner of whichever position you have passed and afterwards get data from it.
Similarly, you can get view of edittext by using -
EditText edtTxt = view.findViewById(R.id.myEdtTxt);
To see how to get data from database and display that in recyclerview, check the example here - https://github.com/incipientinfo/db-queries
I have been working with Team Blox TreeView for about 3 month now with no issues, but after the update from 0.1.0 to (0.1.1 or 0.1.2), I have experienced the following strange situation. I have tried to reproduce the situation I have been experiencing using the code below:
1) TreeViewTest.class:--------------
public class TreeViewTest extends AppCompatActivity {
private static final String TAG = "TreeViewTest";
private DrawerLayout dl_treeview_out;
private ActionBarDrawerToggle drawerToggle;
private FrameLayout fl_treeview_out;
private TreeView treev_treeview_out;
private BaseTreeAdapter adapter_out;
private TreeView treev_treeview_in;
private BaseTreeAdapter adapter_in;
private TextView tv_treeview_in;
private Button b_treeview_in;
private View inView;
private TreeNode mCurrentNodeOut;
private TreeNode mCurrentNodeIn;
private List<String> items;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.treeview_out);
items = new ArrayList<String>();
for(int i = 0 ; i<=10 ; i++){
if(i == 0) {
items.add(i, "A" + "_" + "B");
}else{
items.add(i, "A" + i + "_" + "B" + i);
}
}
// Out View -------------------------------- START
dl_treeview_out = (DrawerLayout) findViewById(R.id.dl_treeview_out);
drawerToggle = new ActionBarDrawerToggle(this, dl_treeview_out , R.string.open, R.string.close) {
public void onDrawerOpened(View drawerView) {
invalidateOptionsMenu();
}
public void onDrawerClosed(View view) {
invalidateOptionsMenu();
}
};
try {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}catch (Exception e){
Log.e(TAG , " " , e);
}
treev_treeview_out = (TreeView) dl_treeview_out.findViewById(R.id.treev_treeview_out);
treev_treeview_out.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
mCurrentNodeOut = adapter_out.getNode(i);
if(mCurrentNodeOut.getData().toString().contains("A")){
fl_treeview_out.removeAllViews();
fl_treeview_out.addView(inView);
tv_treeview_in.setText("In View");
b_treeview_in.setText("~");
TreeNode inNode = new TreeNode("B");
adapter_in.setRootNode(inNode);
dl_treeview_out.openDrawer(Gravity.START , true);
}
}
});
adapter_out = new BaseTreeAdapter<ViewHolderOut>(TreeViewTest.this, R.layout.treeview_out_node) {
#NonNull
#Override
public ViewHolderOut onCreateViewHolder(View view) {
return new ViewHolderOut(view);
}
#Override
public void onBindViewHolder(ViewHolderOut viewHolder, Object data, int position) {
viewHolder.tv_out.setText(data.toString());
}
};
treev_treeview_out.setAdapter(adapter_out);
TreeNode outNode = new TreeNode("A");
adapter_out.setRootNode(outNode);
fl_treeview_out = (FrameLayout) dl_treeview_out.findViewById(R.id.fl_treeview_out);
// Out View -------------------------------- END
// In View -------------------------------- START
inView = getLayoutInflater().inflate(R.layout.treeview_in , null);
treev_treeview_in = (TreeView) inView.findViewById(R.id.treev_treeview_in);
treev_treeview_in.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
mCurrentNodeIn = adapter_in.getNode(i);
if(mCurrentNodeIn.getData().toString().contains("B")){
Toast.makeText(getApplicationContext() , "Data In: " + mCurrentNodeIn.getData().toString() , Toast.LENGTH_LONG).show();
}
}
});
adapter_in = new BaseTreeAdapter<ViewHolderIn>(TreeViewTest.this, R.layout.treeview_in_node) {
#NonNull
#Override
public ViewHolderIn onCreateViewHolder(View view) {
return new ViewHolderIn(view);
}
#Override
public void onBindViewHolder(ViewHolderIn viewHolder, Object data, int position) {
viewHolder.tv_in.setText(data.toString());
}
};
treev_treeview_in.setAdapter(adapter_in);
tv_treeview_in = (TextView) inView.findViewById(R.id.tv_treeview_in);
b_treeview_in = (Button) inView.findViewById(R.id.b_treeview_in);
b_treeview_in.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
makeSelectListDialog("Select", TreeViewTest.this, items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
try {
String[] data_split = items.get(i).split("_");
if(data_split.length == 2){
if(data_split[0].contains("A") && data_split[1].contains("B")){
mCurrentNodeOut.setData(data_split[0]);
adapter_in.getNode(0).setData(data_split[1]);
adapter_in.notifyDataChanged(adapter_in.getNode(0));
adapter_out.notifyDataChanged(mCurrentNodeOut);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
}).show();
}
});
// In View -------------------------------- END
}
private class ViewHolderOut {
CardView cv_out;
TextView tv_out;
ViewHolderOut(View view) {
cv_out = (CardView) view.findViewById(R.id.cv_out);
tv_out = (TextView) cv_out.findViewById(R.id.tv_out);
}
}
private class ViewHolderIn {
CardView cv_in;
TextView tv_in;
ViewHolderIn(View view) {
cv_in = (CardView) view.findViewById(R.id.cv_in);
tv_in = (TextView) cv_in.findViewById(R.id.tv_in);
}
}
public static <T> AlertDialog makeSelectListDialog(String prompt,
Context finalContext, List<T> listItems, final DialogInterface.OnClickListener onYesListener,
final DialogInterface.OnClickListener onNoListener) {
final ArrayAdapter<T> adapt =
new ArrayAdapter<T>(finalContext, android.R.layout.select_dialog_item, listItems);
AlertDialog a = new AlertDialog.Builder(finalContext)
.setTitle(prompt)
.setAdapter(adapt, onYesListener)
.setNegativeButton("Cancel", onNoListener)
.create();
return a;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}else {
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
}
2) treeview_out.xml:--------------------
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/dl_treeview_out"
android:layout_width="match_parent"
android:background="#android:color/white"
android:layout_height="match_parent">
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff">
<de.blox.treeview.TreeView
android:id="#+id/treev_treeview_out"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:useMaxSize="true"
app:lineColor="#android:color/holo_blue_dark"/>
</android.support.design.widget.CoordinatorLayout>
<FrameLayout
android:layout_width="320dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:id="#+id/fl_treeview_out">
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
3) treeview_out_node.xml:---------
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/cv_out"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dp"
card_view:cardElevation="18dp"
card_view:contentPadding="11dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/tv_out"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:textColor="?attr/colorAccent"
android:textStyle="bold"/>
</LinearLayout>
</android.support.v7.widget.CardView>
4) treeview_in.xml:----------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:weightSum="100"
android:id="#+id/ll_treeview_in"
android:layout_gravity="start">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_weight="10"
android:background="#color/colorPrimaryDark"
android:layout_gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="50dp"
android:textStyle="bold"
android:gravity="center"
android:layout_toStartOf="#id/b_treeview_in"
android:layout_alignParentStart="true"
android:layout_gravity="center"
android:background="?attr/colorPrimary"
android:textColor="#android:color/white"
android:id="#+id/tv_treeview_in"/>
<Button
android:layout_width="wrap_content"
android:layout_height="45dp"
android:layout_alignParentEnd="true"
android:textAllCaps="false"
android:layout_marginEnd="2.5dp"
android:layout_marginStart="2.5dp"
android:layout_marginTop="2.5dp"
android:layout_marginBottom="2.5dp"
android:textColor="#android:color/white"
android:background="#color/colorPrimary"
android:layout_gravity="center"
android:gravity="center"
android:id="#+id/b_treeview_in"/>
</RelativeLayout>
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_weight="90"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#fff">
<de.blox.treeview.TreeView
android:id="#+id/treev_treeview_in"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:levelSeparation="20dp"
app:lineColor="#android:color/holo_green_light"/>
</android.support.design.widget.CoordinatorLayout>
</LinearLayout>
5) treeview_in_node.xml:-------------------
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/cv_in"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dp"
card_view:cardElevation="18dp"
card_view:contentPadding="11dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/tv_in"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:textColor="?attr/colorAccent"
android:textStyle="bold"/>
</LinearLayout>
</android.support.v7.widget.CardView>
6) In the code above, I have created two TreeViews (one directly inside activity and another one inside a drawer in this activity) with one block each. First TreeView block contains data starting with A (A , A1 , A2 , ...), where as Second TreeView block contains data starting with B (B , B1 , B2 , ...). The idea here is that I'm trying to change the data of first TreeView block and second TreeView block at the same time by clicking a button from inside the drawer (b_treeview_in) and selecting data from a list which opens. The above code works properly (data of both TreeView blocks is getting updated) in version 0.1.0 of this library, but not working properly (First TreeView block data is getting updated, but the second TreeView block data is not) after the update to version (0.1.1 or 0.1.2). Note: In both cases if I check the data, I find that it changed to what was selected from the list, but visually in case of the second TreeView block it didn't change to what was selected.
7) If this problem is caused by notifyDataChanged() or adapter.getNode(), then why is it working for the first TreeView block?
8)
In case of version 0.1.0
In case of version 0.1.1 or 0.1.2
Developer of TreeView here!
Unfortunatly this issues was causes by the library. I uploaded a new Version, which should fix it. Please try it out.
I define layout row which I inflate and add view pragmatically to a linear layout.
I wanna something like this,
https://i.stack.imgur.com/EKPmJ.png
Here is xml of my main activity where I am inflating the costume view row
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.skw.customeviewdemo.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/inflate"
android:text="inflate"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/list_container">
</LinearLayout>
</LinearLayout>
here is my xml code of row which I am inflating:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="its text view"
/>
<Button
android:id="#+id/nameButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/name"
/>
<ImageView
android:layout_marginTop="-25dp"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/ic_launcher_round"/>
</RelativeLayout>
here is my java code
public class MainActivity extends AppCompatActivity {
Button b;
LinearLayout l1;
Context context;
Boolean isViewCreated = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String Namearray[] = {"sagar", "ranjeet", "akash", "kate"};
this.context = this;
b = (Button) findViewById(R.id.inflate);
l1 = (LinearLayout) findViewById(R.id.list_container);
createViews(Namearray);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(l1.getVisibility() == View.VISIBLE && isViewCreated)
{
l1.setVisibility(View.GONE);
}
else
{
l1.setVisibility(View.VISIBLE);
}
}
});
}
void createViews(final String[] namearray)
{
for(int i=0;i < namearray.length;i++){
final int j = i;
View view = LayoutInflater.from(context).inflate(R.layout.layout_item,null);
TextView button1 = (TextView) view.findViewById(R.id.name);
Button button2 = (Button) view.findViewById(R.id.nameButton);
button1.setText("HELLO " + namearray[i]);
button2.setText("Click to know my name ");
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,"Hello " + namearray[j],Toast.LENGTH_LONG).show();
}
});
view.setId(generateViewId());
try {
l1.addView(view);
isViewCreated = true;
}
catch (Exception e)
{
}
}
l1.setVisibility(View.GONE);
}
private static final AtomicInteger viewIdGenerator = new AtomicInteger(15000000);
public static int generateViewId() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
return generateUniqueViewId();
} else {
return View.generateViewId();
}
}
private static int generateUniqueViewId() {
while (true) {
final int result = viewIdGenerator.get();
// aapt-generated IDs have the high byte nonzero; clamp to the range under that.
int newValue = result + 1;
if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
if (viewIdGenerator.compareAndSet(result, newValue)) {
return result;
}
}
}
}
but when I inflate row my image view get cutoff which I not want I tried with negative margin but it not work
here what it looks like
custom overlapping row
what I do so I over lap image to above view?
Try changing your layout to this.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="its text view"
/>
<Button
android:id="#+id/nameButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/name"
/>
</RelativeLayout>
<ImageView
android:layout_marginTop="25dp"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/ic_launcher_round"/>
</RelativeLayout>
When you put in another row, that row needs to be pushed up so the android icon that is there now overlays it.
I tried to have a grid view with a listview in my activity but I got an error.
Are there any another way to have the below result ?
In my main activity I want to have one a list view display larg imageview and second display them as 2 image per row , should I use grid view or second list view is enough?
this is my code
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fillViewport="true" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="sssss"
android:textSize="16sp"
android:padding="10dp"
android:background="#ffe474" />
<ListView
android:id="#+id/list3"
android:layout_width="wrap_content"
android:layout_height="1500dp"
android:background="#eeeeee" >
</ListView>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text="Recommanded"
android:textSize="18sp"
android:padding="10dp"
android:background="#ffe474" />
<ListView
android:id="#+id/list1"
android:layout_width="wrap_content"
android:layout_height="1500dp"
android:background="#eeeeee" >
</ListView>
</LinearLayout>
</ScrollView>
A more suitable and straightforward solution would be to use RecyclerView with GridLayoutManager. GridLayoutManager takes SpanSizeLookup object which allows you to specify how many spans will each of the items occupy.
A complete solution to this problem includes the following pieces:
Activity with RecyclerView, GridLayoutManager and custom SpanSizeLookup
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
// specify that grid will consist of 2 columns
GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(), 2);
// provide our CustomSpanSizeLookup which determines how many spans each item in grid will occupy
gridLayoutManager.setSpanSizeLookup(new CustomSpanSizeLookup());
// provide our GridLayoutManager to the view
recyclerView.setLayoutManager(gridLayoutManager);
// this is fake list of images
List<Integer> imageResList = getMockedImageList();
// finally, provide adapter to the recycler view
Adapter adapter = new Adapter(imageResList);
recyclerView.setAdapter(adapter);
}
private List<Integer> getMockedImageList() {
// fake images list, you'd need to upload your own image resources
List<Integer> imageResList = new ArrayList<Integer>();
imageResList.add(R.drawable.img1);
imageResList.add(R.drawable.img2);
imageResList.add(R.drawable.img3);
imageResList.add(R.drawable.img4);
imageResList.add(R.drawable.img5);
imageResList.add(R.drawable.img6);
return imageResList;
}
private static class CustomSpanSizeLookup extends GridLayoutManager.SpanSizeLookup {
#Override
public int getSpanSize(int i) {
if(i == 0 || i == 1) {
// grid items on positions 0 and 1 will occupy 2 spans of the grid
return 2;
} else {
// the rest of the items will behave normally and occupy only 1 span
return 1;
}
}
}
}
Adapter for RecyclerView
public class Adapter extends RecyclerView.Adapter {
// I assume that you will pass images as list of resources, but this can be easily switched to a list of URLS
private List<Integer> imageResList = new ArrayList<Integer>();
public Adapter(List<Integer> imageUrlList) {
this.imageResList = imageUrlList;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycle_view_item, viewGroup, false);
return new ItemViewHolder(itemView);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int i) {
ItemViewHolder itemViewHolder = (ItemViewHolder) viewHolder;
itemViewHolder.item.setImageResource(imageResList.get(i));
}
#Override
public int getItemCount() {
return imageResList.size();
}
private static class ItemViewHolder extends RecyclerView.ViewHolder {
private ImageView item;
public ItemViewHolder(View itemView) {
super(itemView);
this.item = (ImageView) itemView.findViewById(R.id.item_image);
}
}
}
activity_main.xml layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
recycler_view_item.xml layout
<?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="150dp"
android:padding="10dp">
<ImageView
android:id="#+id/item_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"/>
</LinearLayout>
And the last piece would be to make sure to add dependency in build.gradle file for RecyclerView:
dependencies {
compile 'com.android.support:recyclerview-v7:21.0.+'
}
And here is the result:
Advantages of this solution are:
it's scalable, lightweight, and very customizable
it's efficient as it recycles the views when you scroll up and down
it does not require messing with touch events which can easily become very tricky to handle once you add any additional touch functionality
I hope this is helpful.
This is little tricky thing, Whenever we get requirement like this, we have to do a workaround like keeping a LinearLayout with orientation as vertical
and keep that LinearLayout inside a ScrollView.
I have created a sample for your issue.. I hope this will help you.
custom_grid_item.xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout_horizontal"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/black">
<LinearLayout
android:id="#+id/gridItemLeft"
android:orientation="horizontal"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:layout_margin="4dp"
android:gravity="left"
android:visibility="invisible">
<TextView
android:id="#+id/itemNameLeft"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="#android:style/TextAppearance.Medium"
android:text="#string/app_name"
android:textColor="#android:color/black"
android:padding="4dp"
android:background="#android:color/white"/>
</LinearLayout>
<LinearLayout
android:id="#+id/gridItemRight"
android:orientation="horizontal"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:layout_margin="4dp"
android:gravity="right"
android:visibility="invisible">
<TextView
android:id="#+id/itemNameRight"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:textAppearance="#android:style/TextAppearance.Medium"
android:text="#string/app_name"
android:textColor="#android:color/black"
android:background="#android:color/white"/>
</LinearLayout>
</LinearLayout>
custom_list_item.xml :
<?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="wrap_content"
android:padding="4dp"
android:background="#android:color/black">
<TextView
android:id="#+id/itemName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="#android:style/TextAppearance.Medium"
android:background="#android:color/white"
android:padding="8dp"
android:text="#string/app_name"
android:textColor="#android:color/black"/>
</LinearLayout>
main.xml :
<?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:background="#android:color/black">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:id="#+id/custom_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white"/>
<LinearLayout
android:orientation="vertical"
android:id="#+id/custom_grid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white"/>
</LinearLayout>
</ScrollView>
</LinearLayout>
MyActivity.java :
public class MyActivity extends Activity {
private List<String> mItems;
private LinearLayout mListLayout, mGridLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mItems = new ArrayList<String>(Arrays.asList("Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7", "Item 8", "Item 9", "Item 10"));
mListLayout = (LinearLayout) findViewById(R.id.custom_list);
mGridLayout = (LinearLayout) findViewById(R.id.custom_grid);
loadListView();
loadGridView();
}
private void loadGridView() {
if (mItems.size() % 2 == 0) {
loadEvenGridView(true);
} else {
loadEvenGridView(false);
LayoutInflater inflater = getLayoutInflater();
LinearLayout gridItem = (LinearLayout) inflater.inflate(R.layout.custom_grid_item, null);
LinearLayout leftItem = (LinearLayout) gridItem.findViewById(R.id.gridItemLeft);
LinearLayout rightItem = (LinearLayout) gridItem.findViewById(R.id.gridItemRight);
leftItem.setVisibility(View.VISIBLE);
rightItem.setVisibility(View.INVISIBLE);
TextView txtItemName = (TextView) gridItem.findViewById(R.id.itemNameLeft);
txtItemName.setText(mItems.get(mItems.size() - 1));
leftItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), mItems.get(mItems.size() - 1), Toast.LENGTH_SHORT).show();
}
});
mGridLayout.addView(gridItem);
}
}
private void loadEvenGridView(boolean isEvenSize) {
int len = mItems.size();
if (!isEvenSize) {
len = len - 1;
}
if (len > 1) {
for (int index = 1; index < len; index += 2) {
LayoutInflater inflater = getLayoutInflater();
LinearLayout gridItem = (LinearLayout) inflater.inflate(R.layout.custom_grid_item, null);
LinearLayout leftItem = (LinearLayout) gridItem.findViewById(R.id.gridItemLeft);
LinearLayout rightItem = (LinearLayout) gridItem.findViewById(R.id.gridItemRight);
TextView txtItemName;
for (int sIndex = 0; sIndex < 2; sIndex++) {
switch (sIndex) {
case 0:
leftItem.setVisibility(View.VISIBLE);
txtItemName = (TextView) gridItem.findViewById(R.id.itemNameLeft);
txtItemName.setText(mItems.get(index - 1));
final int finalIndex = index;
leftItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), mItems.get(finalIndex - 1), Toast.LENGTH_SHORT).show();
}
});
continue;
case 1:
rightItem.setVisibility(View.VISIBLE);
txtItemName = (TextView) gridItem.findViewById(R.id.itemNameRight);
txtItemName.setText(mItems.get(index));
final int finalIndex1 = index;
rightItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), mItems.get(finalIndex1), Toast.LENGTH_SHORT).show();
}
});
continue;
}
}
mGridLayout.addView(gridItem);
}
}
}
private void loadListView() {
for (int index = 0; index < mItems.size(); index++) {
LayoutInflater inflater = getLayoutInflater();
View listItem = inflater.inflate(R.layout.custom_list_item, null);
TextView txtItemName = (TextView) listItem.findViewById(R.id.itemName);
txtItemName.setText(mItems.get(index));
mListLayout.addView(listItem);
final int finalIndex = index;
listItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), mItems.get(finalIndex), Toast.LENGTH_SHORT).show();
}
});
}
}
}
Screenshot :
There is quite easy way to implement this:- AsymmetricGridView
Hope this will help you !!
You cannot simply place a scrollable View inside another scrollable View and expect them to work out of the box, especially if they both scroll in the same direction. The best way to make this possible is by extending those Views and intercepting touch-events that get sent to them. Here you can determine the direction of scroll being made by the user and route the touch event accordingly.
Read this: Intercept Touch Events in a ViewGroup