I have a question about my java code. I would like to open a image as a dialog and then pick the color of the image.
The colorpicker is working fine.
The dialog is working also.(Picture is opening in a popup)
The only problem is when i open the image in the dialog the colorpicker is not working anymore.
Please help?
The code!
public class MainActivity extends AppCompatActivity {
ImageView mImageView;
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View mylayout = LayoutInflater.from(this).inflate(R.layout.activity_2,null);
final ImageView myImage = (ImageView) mylayout.findViewById(R.id.imageView1);
myImage.setDrawingCacheEnabled(true);
myImage.buildDrawingCache(true);
final Button button1 = (Button) findViewById(R.id.button1);
myImage.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE) {
try {
bitmap = myImage.getDrawingCache();
int pixel = bitmap.getPixel((int) event.getX(), (int) event.getY());
//getting RGB values
int r = Color.red(pixel);
int g = Color.green(pixel);
int b = Color.blue(pixel);
//getting Hex value
String hex = "#" + Integer.toHexString(pixel);
//set background color of view
//mColorView.setBackgroundColor(Color.rgb(r,g,b));
System.out.println("r"+r+"g"+g+"b"+b);
// Make the variable a global var easy way
} catch(Exception e){
System.out.println("FOUT JONGUH");
}
}
return true;
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.activity_2);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
});
}
}
MAIN XML:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MainActivity">
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="427dp" />
Second 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"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:srcCompat="#drawable/dirk" />
You need to declare the imageview on dialog not on layout inflater. You can do it like this;
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.activity_2);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
final ImageView myImage = (ImageView) dialog.findViewById(R.id.imageView1); //here is the imageview
dialog.show();
myImage.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE) {
try {
bitmap = myImage.getDrawingCache();
int pixel = bitmap.getPixel((int) event.getX(), (int) event.getY());
//getting RGB values
int r = Color.red(pixel);
int g = Color.green(pixel);
int b = Color.blue(pixel);
//getting Hex value
String hex = "#" + Integer.toHexString(pixel);
//set background color of view
//mColorView.setBackgroundColor(Color.rgb(r,g,b));
System.out.println("r"+r+"g"+g+"b"+b);
// Make the variable a global var easy way
} catch(Exception e){
System.out.println("FOUT JONGUH");
}
}
return true;
}
});
then put your onTouchlistener inside the button.onClickListener
I fixed it by doing this!
// View mColorView;
TextView mResults;
Bitmap bitmap;
String dirk;
Boolean wait = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
webView = (WebView) findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient());
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
mResults = findViewById(R.id.textView4);
//mColorView = findViewById(R.id.colorView);
final Dialog dialog = new Dialog(Activity2.this);
dialog.setContentView(R.layout.popupp);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
final ImageView myImage = (ImageView) dialog.findViewById(R.id.ImageView112);
myImage.setDrawingCacheEnabled(true);
myImage.buildDrawingCache(true);
Button popupje = (Button) findViewById(R.id.popupje);
final Button gereed = (Button) findViewById(R.id.Gereed);
//image view on touch listener
gereed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
wait = true;
if(wait == true) {
myImage.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
try {
bitmap = myImage.getDrawingCache();
int pixel = bitmap.getPixel((int) event.getX(), (int) event.getY());
//getting RGB values
int r = Color.red(pixel);
int g = Color.green(pixel);
int b = Color.blue(pixel);
//set background color of view
//mColorView.setBackgroundColor(Color.rgb(r,g,b));
mResults.setText("RGB" + r + g + b);
// Make the variable a global var easy way
String srtlred = Integer.toString(r);
String srtlblue = Integer.toString(b);
String srtlgreen = Integer.toString(g);
System.out.println("http://192.168.68.158/?r" + srtlred + "g" + srtlgreen + "b" + srtlblue + "&");
webView.loadUrl("http://192.168.68.158/?r" + srtlred + "g" + srtlgreen + "b" + srtlblue + "&");
} catch (Exception e) {
//MEANS THAT THE USER IS GOING OUT OF THE IMAGEVIEW
}
}
return true;
}
});
}
//Makes the correct URL to send to the webview.
//tring srtlred = Integer.toString(red);
//String srtlblue = Integer.toString(blue);
//String srtlgreen = Integer.toString(green);
//System.out.println("http://192.168.68.158/?r"+srtlred +"g"+ srtlgreen+"b" +srtlblue+"&");
//webView.loadUrl("http://192.168.68.158/?r"+srtlred +"g"+ srtlgreen+"b" +srtlblue+"&");
}
});
}
}
Related
I am trying to add bookmark in my web browser and have added it but , it is only saving 1 link . for example if I am at https://www.wikipedia.org/ and save this bookmark
and i browse wikipedia more and landed on this link https://en.wikipedia.org/wiki/Portal:Featured_content
the bookmark will show remove in snack bar and is just saving 1 link and removing 1 link
I want to save both links.
public static final String PREFERENCES = "PREFERENCES_NAME";
public static final String WEB_LINKS = "links";
public static final String WEB_TITLE = "title";
String murl;
//
CoordinatorLayout coordinatorLayout;
private ProgressBar progressBar;
//
android.webkit.WebView webView;
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
webView = (android.webkit.WebView) findViewById(R.id.webview);
progressBar = findViewById(R.id.progressBar);
initWebview();
WebSettings settings = webView.getSettings();
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
murl = getIntent().getExtras().getString("url");
coordinatorLayout = findViewById(R.id.main_content);
settings.setJavaScriptEnabled(true);
settings.setLoadWithOverviewMode(true);
settings.setUseWideViewPort(true);
settings.setSupportZoom(true);
// zoom
settings.setBuiltInZoomControls(true);
// zoom
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
settings.setDomStorageEnabled(true);
webView.setScrollBarStyle(webView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(murl);
webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webView.getSettings().setAppCacheEnabled(true);
// webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
settings.setDomStorageEnabled(true);
// settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
settings.setSaveFormData(true);
settings.setEnableSmoothTransition(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.saved, menu);
SharedPreferences sharedPreferences = getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
String links = sharedPreferences.getString(WEB_LINKS, null);
if (links != null) {
Gson gson = new Gson();
ArrayList<String> linkList = gson.fromJson(links, new TypeToken<ArrayList<String>>() {
}.getType());
if (linkList.contains(murl)) {
menu.getItem(0).setIcon(R.drawable.bookmark);
} else {
menu.getItem(0).setIcon(R.drawable.bookmark);
}
} else {
menu.getItem(0).setIcon(R.drawable.bookmark);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_bookmark) {
String message;
SharedPreferences sharedPreferences = getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
String jsonLink = sharedPreferences.getString(WEB_LINKS, null);
String jsonTitle = sharedPreferences.getString(WEB_TITLE, null);
if (jsonLink != null && jsonTitle != null) {
Gson gson = new Gson();
ArrayList<String> linkList = gson.fromJson(jsonLink, new TypeToken<ArrayList<String>>() {
}.getType());
ArrayList<String> titleList = gson.fromJson(jsonTitle, new TypeToken<ArrayList<String>>() {
}.getType());
if (linkList.contains(murl)) {
linkList.remove(murl);
titleList.remove(webView.getTitle().trim());
Editor editor = sharedPreferences.edit();
editor.putString(WEB_LINKS, new Gson().toJson(linkList));
editor.putString(WEB_TITLE, new Gson().toJson(titleList));
editor.apply();
message = "removed";
} else {
linkList.add(murl);
titleList.add(webView.getTitle().trim());
Editor editor = sharedPreferences.edit();
editor.putString(WEB_LINKS, new Gson().toJson(linkList));
editor.putString(WEB_TITLE, new Gson().toJson(titleList));
editor.apply();
message = "Saved";
}
} else {
ArrayList<String> linkList = new ArrayList<>();
ArrayList<String> titleList = new ArrayList<>();
linkList.add(murl);
titleList.add(webView.getTitle());
Editor editor = sharedPreferences.edit();
editor.putString(WEB_LINKS, new Gson().toJson(linkList));
editor.putString(WEB_TITLE, new Gson().toJson(titleList));
editor.apply();
message = "Saved";
}
Snackbar snackbar = Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_LONG);
snackbar.show();
invalidateOptionsMenu();
}
return super.onOptionsItemSelected(item);
}
private void initWebview() {
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(android.webkit.WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
murl = url;
invalidateOptionsMenu();
}
#Override
public boolean shouldOverrideUrlLoading(android.webkit.WebView view, String url) {
webView.loadUrl(url);
return true;
}
#Override
public boolean shouldOverrideUrlLoading(android.webkit.WebView view, WebResourceRequest request) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
webView.loadUrl(request.getUrl().toString());
}
return true;
}
#Override
public void onPageFinished(android.webkit.WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
invalidateOptionsMenu();
}
#Override
public void onReceivedError(android.webkit.WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
progressBar.setVisibility(View.GONE);
invalidateOptionsMenu();
}
});
}
}
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:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
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="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ProgressBar
android:id="#+id/progressBar"
style="#style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="-7dp"
android:indeterminate="true"
android:visibility="gone"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
I am trying to get an image to move, either to the Left Or Right, when the user touches either the Left Or Right of their device's screen. I have the following code....I have run the Emulator, in Android Studio, and when I click on the Right or Left sides of the Emulator's Screen....nothing happens. What is wrong with this code? All answers are welcome! I have entered the following code in the Activity that has the image I want to move:
public class GameScreen1 extends AppCompatActivity implements View.OnTouchListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_screen1);
ImageView circle1 = (ImageView) findViewById(R.id.circle1);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (v.getId()) {
case R.id.circle1:
if (event.getAction() == MotionEvent.ACTION_DOWN) {
//WHAT CODE SHOULD I PUT INSTEAD OF THE FLOAT X AND X++
int ScreenWidth = getResources().getDisplayMetrics().widthPixels;
float Xtouch = event.getRawX();
int sign = Xtouch > 0.5*ScreenWidth ? 1 : -1;
float XToMove = 50;
int durationMs = 50;
v.animate().translationXBy(sign*XToMove).setDuration(durationMs);
}
break;
}
return false;
}
}
Add ID to your root layout in the activity and add TouchListener on it.
Here's an example:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="#+id/cl_root"
android:layout_height="match_parent"
tools:context=".MainActivity">
</android.support.constraint.ConstraintLayout>
And This is the code of your activity:
public class MainActivity extends AppCompatActivity {
ConstraintLayout layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = findViewById(R.id.cl_root);
layout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int screenWidth = getResources().getDisplayMetrics().widthPixels;
int x = (int)event.getX();
if ( x >= ( screenWidth/2) ) {
//Right touch
}else {
//Left touch
}
return false;
}
});
}
}
I´m making a simple game where user clicks and score will increase its value. If score is on some point like 200, beast will evolve on different imageView and so on.
Problem is that if I reach point in my if statement it works but when I change activity by clicking upper button and then change it back to the mainActivity Progress bar change its state to different value, than i click and it shows correct filling.
How can it be fixed? I need also progress saves itself and fill the bar after closing and opening the app.... I have Score and Proggress values saved in SharedPreferences so i don´t know where is problem. (sorry for EN). Adding some pictures to make it easier to understand.
My Main Activity's code:
public class MainActivity extends Activity
{
int score;
int progress = score;
ImageButton beast;
SoundPool sp = new SoundPool(15, AudioManager.STREAM_MUSIC, 0);
ProgressBar mProgress;
DecimalFormat df = new DecimalFormat("#,###,###");
private ImageView mScanner;
private Animation mAnimation;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
final int soundDd = sp.load(this, R.raw.menu, 1);
mProgress = (ProgressBar) findViewById(R.id.progressBar);
mProgress.getProgressDrawable().setColorFilter(
Color.rgb(0, 199, 140), android.graphics.PorterDuff.Mode.SRC_IN);
mProgress.setScaleY(5f);
fontChange();
addIntegerValue();
mScanner = (ImageView) findViewById(R.id.imageChanger);
mScanner.setVisibility(View.VISIBLE);
mAnimation = new TranslateAnimation(
TranslateAnimation.ABSOLUTE, 0f,
TranslateAnimation.ABSOLUTE, 0f,
TranslateAnimation.RELATIVE_TO_PARENT, 0f,
TranslateAnimation.RELATIVE_TO_PARENT, 0.05f);
mAnimation.setDuration(2000);
mAnimation.setRepeatCount(- 1);
mAnimation.setRepeatMode(Animation.REVERSE);
mAnimation.setInterpolator(new LinearInterpolator());
mScanner.setAnimation(mAnimation);
score = PreferenceManager.getDefaultSharedPreferences(this).getInt("value", score);
TextView ts = (TextView) findViewById(R.id.textview2);
beast = (ImageButton) findViewById(R.id.beastButton);
beast.setSoundEffectsEnabled(false);
if (progress >= 0 && progress <= 199)
{
mProgress.setMax(200);
mScanner.setBackgroundResource(R.drawable.worm);
}
if (progress >= 200 && progress <= 399)
{
mProgress.setMax(400);
mScanner.setBackgroundResource(R.drawable.worm);
}
if (progress >= 400 && progress <= 599)
{
mProgress.setMax(600);
mScanner.setBackgroundResource(R.drawable.worm);
}
if (progress >= 600 && progress <= 799)
{
mProgress.setMax(800);
mScanner.setBackgroundResource(R.drawable.worm);
}
beast.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
sp.play(soundDd, 1, 1, 0, 0, 1);
Intent i = new Intent(getApplicationContext(), BeastSelect.class);
startActivity(i);
}
});
}
public void fontChange()
{
//font set
TextView ts = (TextView) findViewById(R.id.textview2);
TextView tl = (TextView) findViewById(R.id.textLadder);
TextView tb = (TextView) findViewById(R.id.textBeast);
TextView te = (TextView) findViewById(R.id.textevolve);
int low = PreferenceManager.getDefaultSharedPreferences(this).getInt("value", score);
mProgress.setProgress(low);
ts.setText("SCORE : " + " " + df.format(low));
Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/Phage Regular.otf");
ts.setTypeface(custom_font);
tl.setTypeface(custom_font);
tb.setTypeface(custom_font);
te.setTypeface(custom_font);
//font set over
}
public void addIntegerValue()
{
RelativeLayout rl = (RelativeLayout) findViewById(R.id.activity_main);
rl.setSoundEffectsEnabled(false);
final TextView ts = (TextView) findViewById(R.id.textview2);
final int soundId = sp.load(this, R.raw.coin, 1);
rl.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
score++;
mProgress.setProgress(score);
sp.play(soundId, 1, 1, 0, 0, 1);
ts.setText("SCORE : " + " " + df.format(score));
if (progress >= 0 && progress <= 199)
{
mProgress.setMax(200);
mScanner.setBackgroundResource(R.drawable.worm);
}
if (progress >= 200 && progress <= 399)
{
mProgress.setMax(400);
mScanner.setBackgroundResource(R.drawable.worm);
}
if (progress >= 400 && progress <= 599)
{
mProgress.setMax(600);
mScanner.setBackgroundResource(R.drawable.worm);
}
if (progress >= 600 && progress <= 799)
{
mProgress.setMax(800);
mScanner.setBackgroundResource(R.drawable.worm);
}
}
});
}
protected void onPause()
{
super.onPause();
PreferenceManager.getDefaultSharedPreferences(this).edit().putInt("value", score).apply();
}
protected void onDestroy()
{
super.onDestroy();
sp.release();
sp = null;
}
}
My Second Activity's code:
public class BeastSelect extends Activity
{
ImageButton back;
SoundPool sp = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_beast_select);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
final int soundDd = sp.load(this, R.raw.menu, 1);
back = (ImageButton) findViewById(R.id.imageBack);
back.setSoundEffectsEnabled(false);
fontChange();
back.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
sp.play(soundDd, 1, 1, 0, 0, 1);
Intent b = new Intent(getApplicationContext(), MainActivity.class);
startActivity(b);
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
{
// do something on back.
Intent b = new Intent(getApplicationContext(), MainActivity.class);
startActivity(b);
return true;
}
return super.onKeyDown(keyCode, event);
}
public void fontChange()
{
//font set
TextView hd = (TextView) findViewById(R.id.beasttext);
TextView cm = (TextView) findViewById(R.id.textcommon);
TextView tm = (TextView) findViewById(R.id.textmedium);
TextView pr = (TextView) findViewById(R.id.textpro);
Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/Phage Regular.otf");
hd.setTypeface(custom_font);
cm.setTypeface(custom_font);
tm.setTypeface(custom_font);
pr.setTypeface(custom_font);
//font set over
}
}
in your activity onResume method do this:
mProgress = (ProgressBar) findViewById(R.id.progressBar);
score = PreferenceManager.getDefaultSharedPreferences(this).getInt("value", score);
mProgress.setProgress(score);
In my app I have a ListView for listing some textviews and buttons ,also have an ImageView on the top,i have added parallax scrollview between this,now I want to add some textviews and buttons dynamically in the ListView . I have this code ;but it is not working.I am a beginner,so I could not find the actual problem. Can anybody help me out,and Please excuse my language problem?
MainActivity.java
public class MainActivity extends Activity {
private int lastTop = 0;
//ImageView image;
ListView listView;
private static int RESULT_LOAD_IMAGE = 1;
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
ArrayAdapter adapter;
ArrayList<String> items = new ArrayList<>();
public void parallax(final View v) {
final Rect r = new Rect();
v.getLocalVisibleRect(r);
if (lastTop != r.top) {
lastTop = r.top;
v.post(new Runnable() {
#Override
public void run() {
v.setY((float) (r.top / 2.0));
}
});
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
//Dynamic textvieww
final LinearLayout lm = (LinearLayout) findViewById(R.id.linear);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
AbsListView.LayoutParams.WRAP_CONTENT, AbsListView.LayoutParams.WRAP_CONTENT);
//Create four
for(int j=0;j<=4;j++)
{
// Create LinearLayout
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
// Create TextView
TextView product = new TextView(this);
product.setText(" Product"+j+" ");
ll.addView(product);
// Create TextView
TextView price = new TextView(this);
price.setText(" $"+j+" ");
ll.addView(price);
// Create Button
final Button btn = new Button(this);
// Give button an ID
btn.setId(j+1);
btn.setText("Add To Cart");
// set the layoutParams on the button
btn.setLayoutParams(params);
final int index = j;
// Set click listener for button
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.i("TAG", "index :" + index);
Toast.makeText(getApplicationContext(),
"Clicked Button Index :" + index,
Toast.LENGTH_LONG).show();
}
});
//Add button to LinearLayout
ll.addView(btn);
//Add button to LinearLayout defined in XML
lm.addView(ll);
}
//EOF Dynamic
View view = getLayoutInflater().inflate(R.layout.header, null, false);
//Image view block
Button buttonLoadImage = (Button) view.findViewById(R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
this.imageView = (ImageView)view.findViewById(R.id.imgView);
Button photoButton = (Button) view.findViewById(R.id.button2);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
//imageview block end
// image = (ImageView) view.findViewById(R.id.image);
listView.addHeaderView(view);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
parallax(imageView);
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
parallax(imageView);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
}
activity_main.xml
<FrameLayout xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="in.zoid.parallaxtutorial.MainActivity">
<LinearLayout
android:id="#+id/linear"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ListView
android:id="#+id/listView"
android:layout_height="wrap_content"
android:layout_width="match_parent" />
</LinearLayout>
</FrameLayout>
header.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linear"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView android:id="#+id/imgView"
android:layout_width="wrap_content"
android:layout_height="200dip"
android:scaleType="centerCrop" ></ImageView>
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:color/black" >
<Button android:id="#+id/buttonLoadPicture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:text="Load Picture"
android:layout_gravity="center"></Button>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Take Picture"
android:layout_alignParentRight="true"/>
</RelativeLayout>
</LinearLayout>
See this Example it may useful to add data dynamically in list view in android
I am trying to draw circle on ImageView at touched point but it draws at left top corner.
My code is
ImageView imageView;
private static int RESULT_LOAD_IMAGE = 1;
Bitmap bmp;
float touchY;
float touchX;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchX = event.getX();
touchY = event.getY();
imageView.setImageBitmap(drawCircle());
break;
default:
break;
}
return false;
}
});
}
private Bitmap drawCircle() {
Bitmap bitmap = bmp.copy(Bitmap.Config.ARGB_4444, true);
bitmap.setPixel(imageView.getWidth(), imageView.getHeight(), 0);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.RED);
canvas.drawCircle(touchX, touchY, 100, paint);
return bitmap;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.getimage:
pickImage();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
private void pickImage() {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null){
Uri uri = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, filePath, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePath[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
bmp = BitmapFactory.decodeFile(picturePath);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
and xml is
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/ic_launcher" />
</RelativeLayout>
I am not getting what is wrong. I want to draw circle at touched point. Any help will be appreciated.
If you would create a new bitmap with the size of ImageView this code would work fine.
However the "bmp" bitmap is probably much larger then the ImageView and is scaled. That's why you get distorted result.