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.
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 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.
Hi all i have a problem with edit text in frament. This elemtn save text after reopening this fragment. It can reproduce if i do this steps
open activity -> open FragmentA ->open FragmentB (with edittext in it)->backPress(and open again FragmentA) -> open FragmentB (again)
After this steps if i am typed before some text its fill it again. I am add this in code: writeReviewText.setText(""); and in xml : android:text="" but nothing helps. It`s look like state of fragment is saves.
Here the code of xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/app_bar_gradient"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#android:color/transparent"
app:layout_scrollFlags="enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/greyReview">
<ScrollView
android:id="#+id/scrollReview"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal">
<FrameLayout
android:id="#+id/recomendRev"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_marginLeft="5dp"
android:layout_weight="1">
<ImageButton
android:id="#+id/leftIb"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/transparent"
android:src="#drawable/review_recomend_left_selector" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:alpha="0.5"
android:src="#drawable/good" />
<TextView
android:id="#+id/leftTv"
style="#style/Base.TextAppearance.AppCompat.Small"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="2dp"
android:background="#android:color/transparent"
android:text="#string/recomend"
android:textColor="#color/fiolet" />
</LinearLayout>
</FrameLayout>
<FrameLayout
android:id="#+id/noRecomendRev"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_marginRight="5dp"
android:layout_weight="1">
<ImageButton
android:id="#+id/rightIb"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/transparent"
android:src="#drawable/review_recomend_right_selector" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="right|bottom"
android:orientation="horizontal">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:alpha="0.5"
android:src="#drawable/bad" />
<TextView
android:id="#+id/rightTv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="2dp"
android:background="#android:color/transparent"
android:text="#string/dontRecomended"
android:textColor="#color/fiolet" />
</LinearLayout>
</FrameLayout>
</LinearLayout>
<EditText
android:id="#+id/writeReviewText"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_margin="5dp"
android:background="#android:color/white"
android:hint="#string/dummyReview"
android:inputType="textCapSentences|textMultiLine"
android:maxLength="2000"
android:text=""
android:maxLines="4" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="15dp"
android:background="#color/darkGreyReview">
<include
android:id="#+id/photosDummy"
layout="#layout/add_photo_dummy"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</include>
<android.support.v7.widget.RecyclerView
android:id="#+id/photosRv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipToPadding="false"
android:visibility="gone" />
</FrameLayout>
</ScrollView>
</android.support.design.widget.CoordinatorLayout>
Here a code of my fragment class:
public class WriteReviewFragment extends Fragment implements Constants, View.OnClickListener, ExpandableListView.OnChildClickListener, CameraInterface {
MainActivity mActivity;
View self;
EditText writeReviewText;
public int GetPixelFromDips(float pixels) {
// Get the screen's density scale
final float scale = getResources().getDisplayMetrics().density;
// Convert the dps to pixels, based on density scale
return (int) (pixels * scale + 0.5f);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.e(TAG, "onCreateView");
self = inflater.inflate(R.layout.write_review_layout, container, false);
mActivity = ((MainActivity) getActivity());
font = DialogsHelper.getRLight(getActivity().getApplicationContext());
user = mActivity.getUser();
width = DialogsHelper.getDisplayWidth(mActivity);
currentlocale = getResources().getConfiguration().locale;
return self;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
Log.e(TAG, "onViewCreated");
super.onViewCreated(view, savedInstanceState);
Toolbar tv = (Toolbar) view.findViewById(R.id.toolbar);
TextView tbTv = (TextView) tv.findViewById(R.id.tolbarTv);
TextView post = (TextView) tv.findViewById(R.id.post);
back = (ImageView) tv.findViewById(R.id.back);
post.setTypeface(font);
tbTv.setTypeface(font);
tags = (RecipientEditTextView) view.findViewById(R.id.chipsView);
tags.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
tags.setAdapter(new BaseRecipientAdapter(getActivity()));
tags.setTypeface(font);
musicExLv = (ExpandableListView) self.findViewById(R.id.expandableListView);
peopleAVGExLv = (ExpandableListView) self.findViewById(R.id.expandableListViewAVG);
peopleIm = (ImageView) self.findViewById(R.id.peopleIm);
musicIm = (ImageView) self.findViewById(R.id.musicIm);
photosDummy = (RelativeLayout) self.findViewById(R.id.photosDummy);
photosRv = (RecyclerView) self.findViewById(R.id.photosRv);
avgpeople = (TextView) self.findViewById(R.id.avgpeople);
musictype = (TextView) self.findViewById(R.id.musictype);
faceControl = (TextView) self.findViewById(R.id.faceControl);
dresCode = (TextView) self.findViewById(R.id.dresCode);
details = (TextView) self.findViewById(R.id.details);
tagsTv = (TextView) self.findViewById(R.id.tags);
rightTv = (TextView) self.findViewById(R.id.rightTv);
leftTv = (TextView) self.findViewById(R.id.leftTv);
writeReviewText = (EditText) self.findViewById(R.id.writeReviewText);
noRecomendRev = (ImageButton) self.findViewById(R.id.rightIb);
recomendRev = (ImageButton) self.findViewById(R.id.leftIb);
dresleftIb = (ImageButton) self.findViewById(R.id.dresleftIb);
dresRightIb = (ImageButton) self.findViewById(R.id.dresRightIb);
faceleftIb = (ImageButton) self.findViewById(R.id.faceleftIb);
faceRightIb = (ImageButton) self.findViewById(R.id.faceRightIb);
faceRightTv = (TextView) self.findViewById(R.id.faceRightTv);
faceleftTv = (TextView) self.findViewById(R.id.faceleftTv);
dresrightTv = (TextView) self.findViewById(R.id.dresrightTv);
dresleftTv = (TextView) self.findViewById(R.id.dresleftTv);
post.setOnClickListener(this);
back.setOnClickListener(this);
dresleftIb.setOnClickListener(this);
dresRightIb.setOnClickListener(this);
faceleftIb.setOnClickListener(this);
faceRightIb.setOnClickListener(this);
noRecomendRev.setOnClickListener(this);
recomendRev.setOnClickListener(this);
photosDummy.setOnClickListener(this);
peopleIm.setOnClickListener(this);
musicIm.setOnClickListener(this);
writeReviewText.setTypeface(font);
avgpeople.setTypeface(font);
musictype.setTypeface(font);
faceControl.setTypeface(font);
dresCode.setTypeface(font);
details.setTypeface(font);
tagsTv.setTypeface(font);
rightTv.setTypeface(font);
leftTv.setTypeface(font);
faceRightTv.setTypeface(font);
faceleftTv.setTypeface(font);
dresrightTv.setTypeface(font);
dresleftTv.setTypeface(font);
StaggeredGridLayoutManager sglm = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL);
photosRv.setLayoutManager(sglm);
//set same size as images preview
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, width / screenPart);
Log.e(TAG, "photosDummy" + (width / screenPart));
photosDummy.setLayoutParams(lp);
if (getArguments() != null) {
Bundle b = getArguments();
if (b.containsKey("foursquare_id")) {
foursquare_id = b.getString("foursquare_id").toString();
} else {
Toast.makeText(getActivity(), "FSQ Id is empty, you can`t post anything", Toast.LENGTH_SHORT).show();
}
}
//change state of arrow marker
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
musicExLv.setIndicatorBoundsRelative(width - GetPixelFromDips(30), width - GetPixelFromDips(10));
peopleAVGExLv.setIndicatorBoundsRelative(width - GetPixelFromDips(30), width - GetPixelFromDips(10));
} else {
musicExLv.setIndicatorBounds(width - GetPixelFromDips(30), width - GetPixelFromDips(10));
peopleAVGExLv.setIndicatorBounds(width - GetPixelFromDips(30), width - GetPixelFromDips(10));
}
prepareMusicList();
preparePeopleList();
writeReviewText.setText("");
writeReviewText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
reviewAdd.setReview_text(s.toString());
}
});
}
And here code how i am open fragment in activity:
public void SetCurentFragment(final int index, int direction, boolean addToBackStack, int type, Bundle bundle) {
if (currentIndex != 5) {
previosIndex = currentIndex;
}
if (index == 1 || index == 2)
DeleteAllFragmentsBackstack();// need for detect if google map is initialize and already in backstack
Fragment fragment;
fragment = getSupportFragmentManager().findFragmentByTag(ReadReviewFragment.class.getClass().getSimpleName());
if (fragment == null) {
if (fragment == null) {
fragment = fragmentArray[index];
}
} else {
fragment = fragmentArray[index];
}
Log.e(TAG, "Open fragment is " + fragment);
if (fragment.getArguments() != null) {
fragment.getArguments().clear(); //for clear arguments if they saved from previous open of fragment(happens when open photos fragment)
}
if (bundle != null) {
if (fragment.getArguments() == null) {
fragment.setArguments(bundle);
} else {
fragment.getArguments().clear();
fragment.setArguments(bundle);
}
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment, fragment.getClass().getSimpleName());
if (addToBackStack) {
transaction.addToBackStack(fragment.getTag());
} else {
transaction.addToBackStack(null);
}
transaction.commitAllowingStateLoss();
Log.e(TAG, "Transaction commit");
currentIndex = index;
if (index == 0 || index == 1 || index == 2) {
SetVisualTabs(index);
}
}
I am debug my code and bundle is empty when i am open FragmentB. And fragmentArray its array of fragments like:
public final Fragment[] fragmentArray = new Fragment[]{
new FragmentA(),//0
new FragmentB(),//1
I am doing chat application. I am using Recyclerview to show the chat to users. If I add a new item to the Recyclerview I am facing two issues. First one is onBindViewHolder is not working second one is scrollToPosition is not working. Sometimes it's working properly but sometimes I am getting these issue's again and again.
Here I have added the initialisation of RecyclerView
compile 'com.android.support:recyclerview-v7:23.2.0'
LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLayoutManager);
ArrayList<String> as = cd.messagesid(dialog.getDialogId());
adapter = new ChatAdapter(_activity, cd.messages(dialog.getDialogId()), as);
recyclerView.setAdapter(adapter);
I am using below method in adapter page to add a new item.
public void add(QBChatMessage qb) {
chatMessages.add(qb);
messageidis.add(qb.getId());
notifyItemInserted(chatMessages.size() - 1);
}
I am using below methods to add item into the recyclerview and to scroll down the recyclerview.
private void scrollDown() {
// messagesContainer.scrollToPosition(adapter.getItemCount() - 1);
// messagesContainer.smoothScrollToPosition(adapter.getItemCount() - 1);
messagesContainer.scrollToPosition(adapter.getItemCount() - 1);
}
Boolean cc = cd.Insert_tbl_chathistory(msg.getDialogId(), msg.getSenderId() + "", msg.getBody(), msg.getId() + "", msg.getDateSent(), "", msg.getReadIds() + "", msg.getDeliveredIds() + "", msg.getRecipientId() + "", 1, 0, "");
if (cc) {
msg.setProperty("SenderID", msg.getSenderId() + "");
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.add(msg);
scrollDown();
}
});
}
It's an My activity xml file
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/transparent"
android:fitsSystemWindows="true">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/transparent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:navigationContentDescription="#string/abc_action_bar_up_description"
app:navigationIcon="?attr/homeAsUpIndicator"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<com.chatapp.contacts.CircleImageView
android:id="#+id/usericon"
android:layout_width="?attr/actionBarSize"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:src="#drawable/ic_profile" />
<com.chatapp.widgets.MaterialRippleLayout
style="#style/RippleStyle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:layout_toRightOf="#+id/usericon"
android:focusable="false"
android:gravity="center_vertical"
app:rippleColor="#color/main_color_grey_400">
<RelativeLayout
android:id="#+id/chat_details"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:gravity="center_vertical"
android:paddingRight="5dp">
<com.chatapp.font.RobotoTextView
android:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/margin_middle"
android:minWidth="122dp"
android:paddingBottom="#dimen/cpb_stroke_width"
android:text=""
android:textAppearance="?android:textAppearanceMedium"
android:textColor="#color/white" />
<com.chatapp.font.RobotoTextView
android:id="#+id/toolbar_typing"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar_title"
android:layout_marginLeft="#dimen/margin_middle"
android:minWidth="122dp"
android:text=""
android:textColor="#color/white" />
</RelativeLayout>
</com.pluggdd.corporate.chatapp.widgets.MaterialRippleLayout>
</android.support.v7.widget.Toolbar>
<vc908.stickerfactory.ui.view.KeyboardHandleRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/sizeNotifierLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/bottom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#fff">
<com.chatapp.font.RobotoEditText
android:id="#+id/messageEdit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/sticker_image"
android:layout_alignTop="#+id/sticker_image"
android:background="#fff"
android:hint=" Message text"
android:inputType="textMultiLine|textCapSentences"
android:maxLines="6"
android:paddingBottom="10dp"
android:paddingLeft="5dp"
android:scrollbars="vertical" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/chatSendButton"
style="#style/Fabsend"
android:layout_alignParentRight="true"
android:layout_below="#+id/messageEdit"
android:layout_marginBottom="3dp"
android:layout_marginRight="10dp"
app:layout_anchor="#+id/container" />
<ImageView
android:id="#+id/stickers_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/chatSendButton"
android:layout_alignParentLeft="true"
android:layout_alignTop="#+id/chatSendButton"
android:layout_below="#+id/messageEdit"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:src="#drawable/smile_icon_24p"
android:tint="#color/colorPrimary" />
<ImageView
android:id="#+id/attach_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/chatSendButton"
android:layout_alignTop="#+id/chatSendButton"
android:layout_below="#+id/messageEdit"
android:layout_toRightOf="#+id/stickers_button"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:src="#drawable/imageshare_icon_24p"
android:tint="#color/colorPrimary" />
<ImageView
android:id="#+id/videoshare_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/chatSendButton"
android:layout_alignTop="#+id/chatSendButton"
android:layout_below="#+id/messageEdit"
android:layout_toRightOf="#+id/attach_button"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:src="#drawable/video_icon_24p"
android:tint="#color/colorPrimary" />
<ImageView
android:id="#+id/loc_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/chatSendButton"
android:layout_alignTop="#+id/chatSendButton"
android:layout_below="#+id/messageEdit"
android:layout_toRightOf="#+id/videoshare_button"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:src="#drawable/location_icon_24p"
android:tint="#color/colorPrimary" />
</RelativeLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/messagesContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/bottom"
android:layout_alignParentLeft="false"
android:layout_alignParentTop="false"
android:background="#android:color/transparent"
android:divider="#null"
android:listSelector="#android:color/transparent"
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll"/>
</RelativeLayout>
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="240dp"
android:layout_alignParentBottom="true" />
</vc908.stickerfactory.ui.view.KeyboardHandleRelativeLayout>
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
Here I have added my adapter xml file
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toplayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/selectableItemBackground"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/txtInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:background="#drawable/roundedcornermsg"
android:gravity="center"
android:textColor="#android:color/white" />
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:orientation="horizontal"
android:weightSum="100">
<TextView
android:id="#+id/front"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="20" />
<LinearLayout
android:id="#+id/contentWithBackground"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_weight="80"
android:background="#drawable/redchat"
android:orientation="vertical">
<com.chatapp.font.RobotoTextView
android:id="#+id/personname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:paddingLeft="5dp"
android:paddingTop="5dp"
android:singleLine="true"
android:text="Mathankumar:"
android:textColor="#color/colorPrimary" />
<TextView
android:id="#+id/txtMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:autoLink="all"
android:minWidth="150dp"
android:paddingLeft="10dp"
android:textColor="#android:color/white" />
<RelativeLayout
android:id="#+id/chat_detnot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="160dp"
android:visibility="gone">
<ImageView
android:id="#+id/sticker_image"
android:layout_width="160dp"
android:layout_height="160dp"
android:layout_gravity="left"
android:autoLink="all" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/chat_det"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="160dp"
android:visibility="gone">
<com.chatapp.widgets.SquareImageView
android:id="#+id/imgView"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_alignParentLeft="true"
android:layout_gravity="left"
android:autoLink="all"
android:scaleType="centerCrop" />
<com.chatapp.circularprogressbar.CircularProgressButton
android:id="#+id/circular_progress_bar_1"
style="#style/CircularProgressBarStyle.3"
android:layout_centerInParent="true" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/rlayouts"
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="#80000000"
android:gravity="center_vertical"
android:minWidth="160dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="right|center_vertical"
android:layout_alignParentRight="true">
<TextView
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text="12.32"
android:textColor="#color/white"
android:paddingRight="#dimen/spacing_medium"
android:textSize="10dp" />
<ImageView
android:id="#+id/msgstatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/time"
android:layout_alignTop="#+id/time"
android:src="#drawable/ic_eye_icon_unread"
android:visibility="visible" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
</FrameLayout>
Here I have added my adapter Java file
public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.MyViewHolder> implements View.OnClickListener, Target {
//Initialisation for objects
public QBChatMessage getItem(int position) {
if (chatMessages != null) {
return chatMessages.get(position);
} else {
return null;
}
}
public Float imagefloatsize;
public int Imageintsize;
public ChatAdapter(ChatActivity context, List<QBChatMessage> chatMessages, ArrayList<String> val) {
this.context = context;
this.chatMessages = chatMessages;
messageidis = val;
blurTransformation = new BlurTransformation(context, BLUR_RADIUS);
mRequestQueue = Volley.newRequestQueue(context);
baseurl = context.getString(R.string.baseurl);
downloadurl = context.getString(R.string.downloadlink);
appname = context.getString(R.string.app_name);
//This Declaration is used to show the Application Crash Reports for Android
Thread.setDefaultUncaughtExceptionHandler(new ACRA_Page(context));
imagefloatsize = convertDpToPixel(200, context);
Imageintsize = Math.round(imagefloatsize);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int position) {
return new MyViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.chat_rv_adapter, parent, false), isFile(getItem(position).getBody()));
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
QBChatMessage chatMessage = getItem(position);
final MyViewHolder vs = holder;
String Showmsg = chatMessage.getProperty("showmsg").toString();
// int SenderID = Integer.parseInt(chatMessage.getProperty("SenderID").toString());
senderID = chatMessage.getProperty("SenderID").toString();
String val[] = Showmsg.split("Mathan%nahtam&idhaya");
holder.personame.setTag("" + position);
String sz = val[0];
boolean isOutgoing = false;
if (sz.equalsIgnoreCase("1") || senderID == null || senderID.equals(userid + "")) {
isOutgoing = true;
} else {
isOutgoing = false;
}
lastPosition = position;
// isOutgoing = chatMessage.getSenderId() == null || chatMessage.getSenderId().equals(currentUser.getId());
setAlignment(holder, isOutgoing, chatMessage);
holder.rlayouts.setTag(chatMessage);
holder.txt_undotext.setTextSize(10);
holder.txt_undoappicon_48.setTextSize(15);
holder.txt_delete.setTextSize(15);
holder.txtMessage.setText(Html.fromHtml("" + chatMessage.getBody() + ""
));
holder.time.setTag("1");
holder.circular_progress_bar_1.setVisibility(View.GONE);
holder.time.setText(Html.fromHtml("<small>" + getTimeText(chatMessage)
));
String s = getDateText(chatMessage);
if (position == 0) {
holder.txtInfo.setVisibility(View.VISIBLE);
holder.txtInfo.setText(Html.fromHtml("<small>" + s
));
} else {
}
}
private void setAlignment(MyViewHolder holder, boolean isOutgoing, final QBChatMessage qb) {
if (isOutgoing) {
if (isFile(qb.getBody())) {
holder.contentWithBG.setBackgroundResource(R.drawable.bluechat);
layoutParams = (LinearLayout.LayoutParams) holder.chat_det.getLayoutParams();
layoutParams.gravity = Gravity.LEFT;
holder.chat_det.setLayoutParams(layoutParams);
holder.time.setTextColor(Color.parseColor("#ffffff"));
} else {
holder.contentWithBG.setBackgroundResource(R.drawable.bluechat);
layoutParams = (LinearLayout.LayoutParams) holder.txtMessage.getLayoutParams();
layoutParams.gravity = Gravity.LEFT;
holder.contentWithBG.setMinimumWidth(160);
holder.txtMessage.setLayoutParams(layoutParams);
holder.txtMessage.setTextColor(Color.parseColor("#ffffff"));
holder.time.setTextColor(Color.parseColor("#ffffff"));
}
} else {
if (context.dialog.getType().equals(QBDialogType.GROUP)) {
holder.personame.setVisibility(View.VISIBLE);
if (name.equals("##Unknown*&%*")) {
QBUser user = ChatService.getInstance().getDialogsUsers().get(Integer.parseInt(senderID));
holder.personame.setText("" + user.getLogin().replace(ChatActivity.loginprefix, "") + " :");
} else {
holder.personame.setText("" + name + " :");
}
} else {
if (qb.getReadIds().size() > 0) {
PrivateChatImpl.readstatus(qb);
holder.personame.setVisibility(View.GONE);
holder.contentWithBG.setBackgroundResource(R.drawable.whitechat);
layoutParams = (LinearLayout.LayoutParams) holder.chat_det.getLayoutParams();
layoutParams.gravity = Gravity.LEFT;
holder.chat_det.setLayoutParams(layoutParams);
holder.time.setTextColor(Color.parseColor("#ffffff"));
} else {
holder.contentWithBG.setMinimumWidth(160);
holder.contentWithBG.setBackgroundResource(R.drawable.whitechat);
layoutParams = (LinearLayout.LayoutParams) holder.txtMessage.getLayoutParams();
layoutParams.gravity = Gravity.LEFT;
layoutParams.setMargins(5, 0, 0, 0);
holder.txtMessage.setLayoutParams(layoutParams);
holder.txtMessage.setTextColor(Color.parseColor("#000000"));
holder.time.setTextColor(Color.parseColor("#000000"));
}
}
}
}
#Override
public int getItemCount() {
return chatMessages.size();
}
public void remove(int position) {
chatMessages.remove(position);
messageidis.remove(position);
notifyItemRemoved(position);
}
public void add(QBChatMessage qb) {
chatMessages.add(qb);
messageidis.add(qb.getId());
notifyItemInserted(chatMessages.size() - 1);
// notifyDataSetChanged();
}
static class MyViewHolder extends RecyclerView.ViewHolder {
public TextView txtMessage, txtInfo, front, time;
public LinearLayout content;
public LinearLayout contentWithBG;
public ImageView msgstatus;
public ImageView sticker_image;
public SquareImageView NimgView;
public RobotoTextView personame, txt_undotext, txt_delete;
public CircularProgressButton circular_progress_bar_1;
public RelativeLayout rlayouts, chat_det, chat_detnot;
public MaterialDesignIconsTextView txt_undoappicon_48;
public FrameLayout toplayout;
MyViewHolder(View v, Boolean s) {
super(v);
//Initialization for these objects
}
}
#Override
public void onClick(View v) {
MyViewHolder holder1 = (MyViewHolder) v.getTag();
//Access the Textview from holder1 like below
int id = v.getId();
}
}
Can you please give me any solution to solve these issues.
I have a custom dialog for my android application.it shows an image and text with two buttons at left and right.Here is my dialog
public class GalleryPopUp extends Dialog {
private Context context;
private ArrayList<Bitmap> bitmapList = null;
private List<News> homeNewsList = null;
private Button btnArrowLeft;
private Button btnArrowRight;
private ImageView imageView;
private int selectedIndex = 0;
private TextView textView;
static final RelativeLayout.LayoutParams FILL = new RelativeLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
public GalleryPopUp(Context context, ArrayList<Bitmap> bitmapList,
List<News> homeNewsList, int selectedIndex) {
super(context, android.R.style.Theme_Translucent_NoTitleBar);
this.context = context;
this.bitmapList = bitmapList;
this.homeNewsList = homeNewsList;
this.selectedIndex = selectedIndex;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.gallery_popup, null);
btnArrowLeft = (Button)view.findViewById(R.id.btnArrowLeft);
btnArrowRight = (Button)view. findViewById(R.id.btnArrowRight);
imageView = (ImageView) view.findViewById(R.id.imageView);
textView = (TextView)view. findViewById(R.id.textView);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageBitmap(bitmapList.get(selectedIndex));
News news = homeNewsList.get(selectedIndex);
textView.setTextSize(15);
textView.setTypeface(TypeFaceUtils.TYPEFACE_THOOLIKA);
textView.setText(news.getNewsTitle());
btnArrowLeft.setOnClickListener(listenerbtnArrowLeft);
btnArrowRight.setOnClickListener(listenerbtnArrowRight);
setContentView(view);
}
private android.view.View.OnClickListener listenerbtnArrowLeft = new android.view.View.OnClickListener() {
#Override
public void onClick(View v) {
selectedIndex = selectedIndex - 1;
if (selectedIndex < homeNewsList.size() && selectedIndex >= 0) {
imageView.setImageBitmap(bitmapList.get(selectedIndex));
News news = homeNewsList.get(selectedIndex);
textView.setTypeface(TypeFaceUtils.TYPEFACE_THOOLIKA);
textView.setText(news.getNewsTitle());
}
else
{
GalleryPopUp.this.dismiss();
}
}
};
private android.view.View.OnClickListener listenerbtnArrowRight = new android.view.View.OnClickListener() {
#Override
public void onClick(View v) {
selectedIndex = selectedIndex + 1;
if (selectedIndex < homeNewsList.size()) {
imageView.setImageBitmap(bitmapList.get(selectedIndex));
News news = homeNewsList.get(selectedIndex);
textView.setTypeface(TypeFaceUtils.TYPEFACE_THOOLIKA);
textView.setText(news.getNewsTitle());
}
else
{
GalleryPopUp.this.dismiss();
}
}
};
}
gallery_popup.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relativeLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/imageView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true" />
<TextView
android:id="#+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView"
android:layout_gravity="center_horizontal|bottom"
android:gravity="center_horizontal"
android:text=""
android:textColor="#000000" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/imageView"
android:gravity="center" >
<Button
android:id="#+id/btnArrowRight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/btn_arrow_right" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignTop="#+id/imageView"
android:gravity="center" >
<Button
android:id="#+id/btnArrowLeft"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:background="#drawable/btn_arrow_left" />
</LinearLayout>
</RelativeLayout>
How can i show this dialog exactly at center of parent.?
The best way is to change your layout like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
>
try it and let me know if it works.
<TextView
android:id="#+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView"
android:layout_gravity="center_horizontal|bottom"
android:gravity="center_horizontal"
android:text=""
android:textColor="#000000" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/imageView"
android:gravity="center" >
<Button
android:id="#+id/btnArrowRight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/btn_arrow_right" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignTop="#+id/imageView"
android:gravity="center" >
<Button
android:id="#+id/btnArrowLeft"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:background="#drawable/btn_arrow_left" />
</LinearLayout>
</RelativeLayout>
</RelativeLayout>