custom view with overlapping - android

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.

Related

Fragment editText data getting cleared when i am moving to another activity and coming back

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();
}
});

dynamic add-view with ID

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

problems with scrollview (android-studio)

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

Android Listview button doesn't work

I created a custom listview with the base adapter, but for some reason can not click on the button inside the individual list views.
Here is the code the the main 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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Light List"
android:id="#+id/lightName"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/loginbutton"
android:id="#+id/button"
android:onClick="buttonClicked"
android:layout_alignParentBottom="true"
android:layout_alignLeft="#+id/lightName"
android:layout_alignStart="#+id/lightName" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/lightList"
android:layout_below="#+id/lightName"
android:layout_above="#+id/button"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
</RelativeLayout>
Here is the code for views in the list:
<?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:id="#+id/lightList"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/lightName"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/statusText"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/buttonoff"
android:focusable="true"
android:enabled="true"
android:clickable="true" />
</LinearLayout>
Lastly here is the adapter code:
public ArrayList<myLight> dataSet = new ArrayList<myLight>();
public void makeLightList(ArrayList<myLight> lights) {
Iterator<myLight> iter = lights.iterator();
while(iter.hasNext()) {
dataSet.add(iter.next());
}
}
#Override
public int getCount() {
return dataSet.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v;
LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.lightlistlayout, null);
TextView name = (TextView) findViewById(R.id.lightName);
name.setText(dataSet.get(position).name);
TextView status = (TextView) findViewById(R.id.statusText);
if(dataSet.get(position).reachable) {
if(dataSet.get(position).isOn) {
status.setText("Light is On");
} else {
status.setText("Light is Off");
}
} else {
status.setText("Light is currently not reachable");
}
dataHolder dh = new dataHolder();
dh.name = dataSet.get(position).name;
//Handle Off button click from list view
Button offButton = (Button) findViewById(R.id.buttonoff);
offButton.setTag(dh);
offButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dataHolder dhv = new dataHolder();
dhv = (dataHolder)v.getTag();
Toast.makeText(getBaseContext(), dhv.name + " Turned Off", Toast.LENGTH_LONG).show();
}
});
return v;
}
};
I am not sure if my onclicklistener is correct as I can't click on the button at all yet. Here is a picture showing the button. I have messed with different focus and clickable settings in the xml file and no luck. I added a seeker bar that I was able to slide that back and forth, but the button will not let me click it.
v = inflater.inflate(R.layout.lightlistlayout, null);
Here you have inflated the row file for your adapter and the below are your id initialization and for that you have not added your view to your id, so try this.
TextView name = (TextView) v.findViewById(R.id.lightName);
TextView status = (TextView) v.findViewById(R.id.statusText);
Button offButton = (Button) v.findViewById(R.id.buttonoff);
try changing
android:focusable="true" to android:focusable="false" in Button's xml

Adapting a layout using a Dialog Fragment

I'm trying to adapt a layout in a dialog fragment to show an imageview, a text view and two butttons, but I have problem adapting the layout in it.
I get this:
http://kitsord.com/imagestack/Screenshot_2014-05-22-11-35-22.png
And the output should look something like this:
http://kitsord.com/imagestack/looks.png
So I don't know why the text and the buttons don't show correctly.
The DialogFragment is this one:
public class LearnFragment extends DialogFragment {
ImageView imgC;
VideoView myVideoView;
View root ;
TextView textv ;
ImageButton next , atras;
Integer contador;
public static LearnFragment newInstance() {
LearnFragment f = new LearnFragment();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
contador = GridViewFragmet.positionarchivo; // this is a static variable from another class
if (getDialog() != null) {
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getDialog().getWindow().setBackgroundDrawableResource(android.R.color.transparent);
}
LayoutInflater inflaterr = getActivity().getLayoutInflater();
root = inflaterr.inflate(R.layout.aprender_fragment_display, null);
myVideoView = (VideoView)root.findViewById(R.id.videos_aprender);
imgC =(ImageView) root.findViewById(R.id.imagenes_aprender);
textv = (TextView) root.findViewById(R.id.text_aprender);
next = (ImageButton) root.findViewById(R.id.btnnext_aprender);
atras = (ImageButton) root.findViewById(R.id.btnatras_aprender);
myVideoView.setVisibility(View.GONE);
imgC.setVisibility(View.GONE);
textv.setVisibility(-1);
if(contador == 0) {
atras.setVisibility(-1);
} else if(contador > 0 && contador < LearnAdapter.imagenesAprender.size() - 1){
next.setVisibility(0);
atras.setVisibility(0);
} else if(contador == LearnAdapter.imagenesAprender.size() - 1) {
next.setVisibility(-1);
}
startIt(GridViewFragmet.nombrearchivo);
next.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
myVideoView.setVisibility(View.GONE);
imgC.setVisibility(View.GONE);
textv.setVisibility(-1);
if(contador + 1 < LearnAdapter.imagenesAprender.size()){
++contador;
startIt(LearnAdapter.imagenesAprender.get(contador));
atras.setVisibility(0);
if(contador == LearnAdapter.imagenesAprender.size() - 1){
next.setVisibility(-1);
}
}
}
});
atras.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
myVideoView.setVisibility(View.GONE);
imgC.setVisibility(View.GONE);
textv.setVisibility(-1);
if(contador - 1 >= 0){
--contador;
startIt(LearnAdapter.imagenesAprender.get(contador));
next.setVisibility(0);
if(contador == 0) {
atras.setVisibility(-1);
}
}
}
});
return root;
}
public void startIt(String archivo){
if(archivo.substring(archivo.lastIndexOf(".") + 1).equals(variablesGlobales.IMAGENES.obtenerinfo())) {
textv.setVisibility(0);
textv.setText(archivo.substring(archivo.lastIndexOf("/")+1, archivo.lastIndexOf(".")));
imgC.setVisibility(View.VISIBLE);
Bitmap bmp = BitmapFactory.decodeFile(archivo);
imgC.setImageBitmap(bmp);
} else {
textv.setVisibility(0);
textv.setText(archivo.substring(archivo.lastIndexOf("/")+1, archivo.lastIndexOf(".")));
myVideoView.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
}
});
myVideoView.setVisibility(View.VISIBLE);
myVideoView.setZOrderOnTop(true);
myVideoView.setVideoPath(archivo);
myVideoView.start();
}
}
#SuppressWarnings("deprecation")
#Override
public void onStart() {
super.onStart();
// change dialog width
if (getDialog() != null) {
int fullWidth = getDialog().getWindow().getAttributes().width;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
fullWidth = size.x;
} else {
Display display = getActivity().getWindowManager().getDefaultDisplay();
fullWidth = display.getWidth();
}
final int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
.getDisplayMetrics());
int w = fullWidth - padding;
int h = getDialog().getWindow().getAttributes().height;
getDialog().getWindow().setLayout(w, h);
}
}
}
The layout is this one:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/ll1"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_weight="1" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="horizontal" >
<VideoView
android:id="#+id/videos_aprender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />
<ImageView
android:id="#+id/imagenes_aprender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:src="#drawable/abc" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/ll2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.4"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="1">
<TextView
android:id="#+id/text_aprender"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#0f9f9f"
android:gravity="center"
android:text="Large Text"
android:textAlignment="center"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#fff"
android:textSize="25dp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/ll3"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.8" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="1" >
<ImageButton
android:id="#+id/btnatras_aprender"
style="?android:attr/buttonStyleSmall"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="#00FFFFFF"
android:src="#drawable/arrow_izq" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="0.9">
<ImageButton
android:id="#+id/btnnext_aprender"
style="?android:attr/buttonStyleSmall"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="#00FFFFFF"
android:src="#drawable/arrow_der" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
I found my problem. The problem was at my class of Dialog Fragment.
The line that was giving me the error was this one:
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
That was what affected the whole dialog and moved the layout.

Categories

Resources